Пример #1
0
my_bool my_thread_global_init(void)
{
  if (pthread_key_create(&THR_KEY_mysys,free))
  {
    fprintf(stderr,"Can't initialize threads: error %d\n",errno);
    exit(1);
  }
#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
  pthread_mutexattr_init(&my_fast_mutexattr);
  pthread_mutexattr_setkind_np(&my_fast_mutexattr,PTHREAD_MUTEX_ADAPTIVE_NP);
#endif
#ifdef PPTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
  pthread_mutexattr_init(&my_errchk_mutexattr);
  pthread_mutexattr_setkind_np(&my_errchk_mutexattr,
			       PTHREAD_MUTEX_ERRORCHECK_NP);
#endif
  THR_KEY_mysys_initialized= TRUE;
#ifdef HAVE_OPENSSL
  pthread_mutex_init(&LOCK_ssl_config,MY_MUTEX_INIT_FAST);
#endif
  pthread_mutex_init(&THR_LOCK_malloc,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_open,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_lock,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_net,MY_MUTEX_INIT_FAST);
#ifdef _WIN32
  /* win_pthread_init(); */
#endif
#ifndef HAVE_LOCALTIME_R
  pthread_mutex_init(&LOCK_localtime_r,MY_MUTEX_INIT_SLOW);
#endif
  return my_thread_init();
}
Пример #2
0
static void*
client_thread(	void*	arg)
{
  my_thread_init();
  do_ssl_stuff((TH_ARGS*)arg);
  return 0;
}
Пример #3
0
/*
  pin allocator - alloc and release an element in a loop
*/
pthread_handler_t test_lf_pinbox(void *arg)
{
  int    m= *(int *)arg;
  int32 x= 0;
  LF_PINS *pins;

  if (with_my_thread_init)
    my_thread_init();

  pins= lf_pinbox_get_pins(&lf_allocator.pinbox);

  for (x= ((int)(intptr)(&m)); m ; m--)
  {
    lf_pinbox_put_pins(pins);
    pins= lf_pinbox_get_pins(&lf_allocator.pinbox);
  }
  lf_pinbox_put_pins(pins);
  pthread_mutex_lock(&mutex);
  if (!--running_threads) pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);

  if (with_my_thread_init)
    my_thread_end();

  return 0;
}
Пример #4
0
my_bool my_thread_global_init(void)
{
  int pth_ret;

  /* Normally this should never be called twice */
  DBUG_ASSERT(my_thread_global_init_done == 0);
  if (my_thread_global_init_done)
    return 0;
  my_thread_global_init_done= 1;

  if ((pth_ret= pthread_key_create(&THR_KEY_mysys, NULL)) != 0)
  {
    fprintf(stderr, "Can't initialize threads: error %d\n", pth_ret);
    return 1;
  }

  /* Mutex used by my_thread_init() and after my_thread_destroy_mutex() */
  my_thread_init_internal_mutex();

  if (my_thread_init())
    return 1;

  thd_lib_detected= get_thread_lib();

  my_thread_init_common_mutex();

  return 0;
}
Пример #5
0
pthread_handler_t test_lf_hash(void *arg)
{
  int    m= (*(int *)arg)/(2*N_TLH);
  int32 x,y,z,sum= 0, ins= 0, scans= 0;
  LF_PINS *pins;

  if (with_my_thread_init)
    my_thread_init();

  pins= lf_hash_get_pins(&lf_hash);

  for (x= ((int)(intptr)(&m)); m ; m--)
  {
    int i;
    y= x;
    for (i= 0; i < N_TLH; i++)
    {
      x= (x*(m+i)+0x87654321) & INT_MAX32;
      z= (x<0) ? -x : x;
      if (lf_hash_insert(&lf_hash, pins, &z))
      {
        sum+= z;
        ins++;
      }
      else
      {
        int unused= 0;
        lf_hash_iterate(&lf_hash, pins, do_sum, &unused);
        scans++;
      }
    }
    for (i= 0; i < N_TLH; i++)
    {
      y= (y*(m+i)+0x87654321) & INT_MAX32;
      z= (y<0) ? -y : y;
      if (lf_hash_delete(&lf_hash, pins, (uchar *)&z, sizeof(z)))
        sum-= z;
    }
  }
  lf_hash_put_pins(pins);
  pthread_mutex_lock(&mutex);
  bad+= sum;
  inserts+= ins;

  if (--N == 0)
  {
    diag("%d mallocs, %d pins in stack, %d hash size, %d inserts, %d scans",
         lf_hash.alloc.mallocs, lf_hash.alloc.pinbox.pins_in_array,
         lf_hash.size, inserts, scans);
    bad|= lf_hash.count;
  }
  if (!--running_threads) pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);
  if (with_my_thread_init)
    my_thread_end();
  return 0;
}
Пример #6
0
my_bool my_thread_global_init(void)
{
  if (pthread_key_create(&THR_KEY_mysys,0))
  {
    fprintf(stderr,"Can't initialize threads: error %d\n",errno);
    return 1;
  }

#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
  /*
    Set mutex type to "fast" a.k.a "adaptive"

    The mutex kind determines what happens if a thread attempts to lock
    a mutex it already owns with pthread_mutex_lock(3). If the mutex
    is of the ``fast'' kind, pthread_mutex_lock(3) simply suspends
    the calling thread forever. If the mutex is of the ``error checking''
    kind, pthread_mutex_lock(3) returns immediately with the error
    code EDEADLK.
  */
  pthread_mutexattr_init(&my_fast_mutexattr);
  pthread_mutexattr_settype(&my_fast_mutexattr,
                            PTHREAD_MUTEX_ADAPTIVE_NP);
#endif
#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
  /*
    Set mutex type to "errorcheck" a.k.a "adaptive"
  */
  pthread_mutexattr_init(&my_errorcheck_mutexattr);
  pthread_mutexattr_settype(&my_errorcheck_mutexattr,
                            PTHREAD_MUTEX_ERRORCHECK);
#endif

  pthread_mutex_init(&THR_LOCK_malloc,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_open,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_lock,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_isam,MY_MUTEX_INIT_SLOW);
  pthread_mutex_init(&THR_LOCK_myisam,MY_MUTEX_INIT_SLOW);
  pthread_mutex_init(&THR_LOCK_heap,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_net,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_charset,MY_MUTEX_INIT_FAST);
#if defined( __WIN__) || defined(OS2)
  win_pthread_init();
#endif
#if !defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)
  pthread_mutex_init(&LOCK_localtime_r,MY_MUTEX_INIT_SLOW);
#endif
#ifndef HAVE_GETHOSTBYNAME_R
  pthread_mutex_init(&LOCK_gethostbyname_r,MY_MUTEX_INIT_SLOW);
#endif
  if (my_thread_init())
  {
    my_thread_global_end();			/* Clean up */
    return 1;
  }
  return 0;
}
Пример #7
0
pthread_handler_t pthread_start(void *param)
{
  pthread_handler func=((struct pthread_map *) param)->func;
  void *func_param=((struct pthread_map *) param)->param;
  my_thread_init();			/* Will always succeed in windows */
  pthread_mutex_lock(&THR_LOCK_thread);	  /* Wait for beginthread to return */
  win_pthread_self=((struct pthread_map *) param)->pthreadself;
  pthread_mutex_unlock(&THR_LOCK_thread);
  free((char*) param);			  /* Free param from create */
  pthread_exit((void*) (*func)(func_param));
  return 0;				  /* Safety */
}
Пример #8
0
static
void *audit_log_flush_worker(void *arg)
{
  audit_log_buffer_t *log= (audit_log_buffer_t*) arg;

  my_thread_init();
  while (!(log->stop && log->flush_pos == log->write_pos))
  {
    audit_log_flush(log);
  }
  my_thread_end();

  return NULL;
}
Пример #9
0
pthread_handler_t test_lf_alloc(void *arg)
{
  int    m= (*(int *)arg)/2;
  int32 x,y= 0;
  LF_PINS *pins;

  if (with_my_thread_init)
    my_thread_init();

  pins= lf_alloc_get_pins(&lf_allocator);

  for (x= ((int)(intptr)(&m)); m ; m--)
  {
    TLA *node1, *node2;
    x= (x*m+0x87654321) & INT_MAX32;
    node1= (TLA *)lf_alloc_new(pins);
    node1->data= x;
    y+= node1->data;
    node1->data= 0;
    node2= (TLA *)lf_alloc_new(pins);
    node2->data= x;
    y-= node2->data;
    node2->data= 0;
    lf_alloc_free(pins, node1);
    lf_alloc_free(pins, node2);
  }
  lf_alloc_put_pins(pins);
  pthread_mutex_lock(&mutex);
  bad+= y;

  if (--N == 0)
  {
    diag("%d mallocs, %d pins in stack",
         lf_allocator.mallocs, lf_allocator.pinbox.pins_in_array);
#ifdef MY_LF_EXTRA_DEBUG
    bad|= lf_allocator.mallocs - lf_alloc_pool_count(&lf_allocator);
#endif
  }
  if (!--running_threads) pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);

  if (with_my_thread_init)
    my_thread_end();
  return 0;
}
Пример #10
0
pthread_handler_t ThreadOpen(void *p)
  {
  PTBMT cmp = (PTBMT)p;

  if (!my_thread_init()) {
    set_current_thd(cmp->Thd);

    // Try to open the connection
    if (!cmp->Tap->GetTo_Tdb()->OpenDB(cmp->G)) {
      cmp->Ready = true;
    } else
      cmp->Rc = RC_FX;

    my_thread_end();
  } else
    cmp->Rc = RC_FX;

  return NULL;
  } // end of ThreadOpen
Пример #11
0
static void *test_thread_writer(void *arg)
{
  int param=*((int*) arg);
  my_thread_init();
  {
    DBUG_ENTER_NO_RETURN("test_writer");

    writer(param);

    DBUG_PRINT("info", ("Thread %s ended", my_thread_name()));
    pthread_mutex_lock(&LOCK_thread_count);
    ok(1, "writer%d: done", param);
    thread_count--;
    pthread_cond_signal(&COND_thread_count); /* Tell main we are ready */
    pthread_mutex_unlock(&LOCK_thread_count);
    free((uchar*) arg);
    my_thread_end();
  }
  return 0;
}
Пример #12
0
static void *
timer_notify_thread_func(void *arg)
{
  sigset_t set;
  siginfo_t info;
  my_timer_t *timer;
  pthread_barrier_t *barrier= arg;

  my_thread_init();

  sigemptyset(&set);
  sigaddset(&set, MY_TIMER_EVENT_SIGNO);
  sigaddset(&set, MY_TIMER_KILL_SIGNO);

  /* Get the thread ID of the current thread. */
  timer_notify_thread_id= (pid_t) syscall(SYS_gettid);

  /* Wake up parent thread, timer_notify_thread_id is available. */
  pthread_barrier_wait(barrier);

  while (1)
  {
    if (sigwaitinfo(&set, &info) < 0)
      continue;

    if (info.si_signo == MY_TIMER_EVENT_SIGNO)
    {
      timer= (my_timer_t*)info.si_value.sival_ptr;
      timer->notify_function(timer);
    }
    else if (info.si_signo == MY_TIMER_KILL_SIGNO)
      break;
  }

  my_thread_end();

  return NULL;
}
Пример #13
0
BOOL APIENTRY LibMain(HANDLE hInst,DWORD ul_reason_being_called,
		      LPVOID lpReserved)
{
  switch (ul_reason_being_called) {
  case DLL_PROCESS_ATTACH:	/* case of libentry call in win 3.x */
    if (!inited++)
    {
      s_hModule=hInst;
      libmysql_init();
      main_thread=GetCurrentThreadId();
    }
    break;
  case DLL_THREAD_ATTACH:
    threads++;
    my_thread_init();
    break;
  case DLL_PROCESS_DETACH:	/* case of wep call in win 3.x */
     if (!--inited)		/* Safety */
     {
       /* my_thread_init() */	/* This may give extra safety */
       my_end(0);
     }
    break;
  case DLL_THREAD_DETACH:
    /* Main thread will free by my_end() */
    threads--;
    if (main_thread != GetCurrentThreadId())
      my_thread_end();
    break;
  default:
    break;
  } /* switch */

  return TRUE;

  UNREFERENCED_PARAMETER(lpReserved);
} /* LibMain */
Пример #14
0
my_bool my_thread_global_init(void)
{
  if (pthread_key_create(&THR_KEY_mysys,free))
  {
    fprintf(stderr,"Can't initialize threads: error %d\n",errno);
    exit(1);
  }
#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
  pthread_mutexattr_init(&my_fast_mutexattr);
  pthread_mutexattr_setkind_np(&my_fast_mutexattr,PTHREAD_MUTEX_ADAPTIVE_NP);
#endif
#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
  pthread_mutexattr_init(&my_errchk_mutexattr);
  pthread_mutexattr_setkind_np(&my_errchk_mutexattr,
			       PTHREAD_MUTEX_ERRORCHECK_NP);
#endif

  pthread_mutex_init(&THR_LOCK_malloc,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_open,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_keycache,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_lock,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_isam,MY_MUTEX_INIT_SLOW);
  pthread_mutex_init(&THR_LOCK_myisam,MY_MUTEX_INIT_SLOW);
  pthread_mutex_init(&THR_LOCK_heap,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_net,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&THR_LOCK_charset,MY_MUTEX_INIT_FAST);
#if defined( __WIN__) || defined(OS2)
  win_pthread_init();
#endif
#ifndef HAVE_LOCALTIME_R
  pthread_mutex_init(&LOCK_localtime_r,MY_MUTEX_INIT_SLOW);
#endif
#ifndef HAVE_GETHOSTBYNAME_R
  pthread_mutex_init(&LOCK_gethostbyname_r,MY_MUTEX_INIT_SLOW);
#endif
  return my_thread_init();
}
Пример #15
0
static TDHS_INLINE THD* init_THD(char* db, const void *stack_bottom,
                                 bool need_write) {
    THD *thd = NULL;
    my_thread_init();
    thd = new THD;
    if (thd == NULL) {
        my_thread_end();
        return NULL;
    }
    thd->thread_stack = (char*) stack_bottom;
    easy_debug_log("TDHS:thread_stack = %p sizeof(THD)=%zu sizeof(mtx)=%zu ",
                   thd->thread_stack, sizeof(THD), sizeof(LOCK_thread_count));
    thd->store_globals();
    thd->system_thread = static_cast<enum_thread_type>(1 << 30UL);
    const NET v = { 0 };
    thd->net = v;
    if (need_write) {
        //for write
#if MYSQL_VERSION_ID >= 50505
        thd->variables.option_bits |= OPTION_BIN_LOG;
#else
        thd->options |= OPTION_BIN_LOG;
#endif
    }
    //for db
    safeFree(thd->db);
    thd->db = db;
    my_pthread_setspecific_ptr(THR_THD, thd);

    tdhs_mysql_mutex_lock(&LOCK_thread_count);
    thd->thread_id = thread_id++;
    threads.append(thd);
    ++thread_count;
    tdhs_mysql_mutex_unlock(&LOCK_thread_count);
    return thd;
}
Пример #16
0
pthread_handler_t test_trnman(void *arg)
{
  uint   x, y, i, n;
  TRN    *trn[MAX_ITER];
  int    m= (*(int *)arg);

  if (my_thread_init())
    BAIL_OUT("my_thread_init failed!");

  for (x= ((int)(intptr)(&m)); m > 0; )
  {
    y= x= (x*3628273133LL + 1500450271LL) % 9576890767LL; /* three prime numbers */
    m-= n= x % MAX_ITER;
    for (i= 0; i < n; i++)
    {
      trn[i]= trnman_new_trn(0);
      if (!trn[i])
      {
        diag("trnman_new_trn() failed");
        litmus++;
      }
    }
    for (i= 0; i < n; i++)
    {
      y= (y*19 + 7) % 31;
      trnman_end_trn(trn[i], y & 1);
    }
  }
  pthread_mutex_lock(&rt_mutex);
  rt_num_threads--;
  pthread_mutex_unlock(&rt_mutex);

  my_thread_end();

  return 0;
}
Пример #17
0
int main(int argc, char*argv[]) {
    //variables
    const config_setting_t *figuras, *figura_actual;
    int count, n;
    int xInit, yInit, xIncremento, yIncremento, xDir, yDir, xFinal, yFinal, rotacion, animacion, colorIn, colorOut, tiempoInicio, tiempoIntervalo,tiempoVida, tipoScheduler, tiquetes;


    
    

    //init socket ***
    cantidad_sockets = 3;
    
    struct sigaction sa;
    sa.sa_handler = &sig_int;
    // Block every signal during the handler
    sigfillset(&sa.sa_mask);
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        printf("Error: cannot handle SIGINT");
    }
    int sock = open_socket();
    if (sock == -1) {
        printf("error occured\n");
        return -1;
    }
    /*Inicializa los sockets de los monitores 1 y 2*/
    /*Inicializa los sockets de los monitores 1 y 2*/
    int contador_sockets;
    for (contador_sockets = 0; contador_sockets < cantidad_sockets; contador_sockets++) {
        if (contador_sockets == 0) {
            socket_monitor_1 = listener((void*) &sock);
            printf("creo monitor 1\n");
        } else if (contador_sockets == 1) {
            socket_monitor_2 = listener((void*) &sock);
            printf("creo monitor 2\n");
        } else if (contador_sockets == 2) {
            socket_monitor_3 = listener((void*) &sock);
            printf("creo monitor 3\n");
        }
    }
    printf("ya cree todos los sockets\n");
    

    my_thread_init();
    
    printf("se hizo el init de my_thread\n");
        
    //init lista
    initLista();
    
      printf("se hizo el init de la lista figuras\n");

    
    //Lectura figuras
    config_t cfg, *cf;
    cf = &cfg;
    config_init(cf);

    if (!config_read_file(cf, "Archivos de Configuracion/test.cfg")) { //directorio archivo
        fprintf(stderr, "%s:%d - %s\n",
                config_error_file(cf),
                config_error_line(cf),
                config_error_text(cf));
        config_destroy(cf);
        return (EXIT_FAILURE);
    }

    figuras = config_lookup(cf, "Figuras");
    count = config_setting_length(figuras);

    for (n = 0; n < count; n++) {
        figura_actual = config_setting_get_elem(figuras, n);
        config_setting_lookup_int(figura_actual, "Xinit", &xInit);
        config_setting_lookup_int(figura_actual, "Yinit", &yInit);
        config_setting_lookup_int(figura_actual, "Xincremento", &xIncremento);
        config_setting_lookup_int(figura_actual, "Yincremento", &yIncremento);
        config_setting_lookup_int(figura_actual, "Xdir", &xDir);
        config_setting_lookup_int(figura_actual, "Ydir", &yDir);
        config_setting_lookup_int(figura_actual, "XFinal", &xFinal);
        config_setting_lookup_int(figura_actual, "YFinal", &yFinal);
        config_setting_lookup_int(figura_actual, "RotacionInit", &rotacion);
        config_setting_lookup_int(figura_actual, "Animacion", &animacion);
        config_setting_lookup_int(figura_actual, "ColorIn", &colorIn);
        config_setting_lookup_int(figura_actual, "ColorOut", &colorOut);
        config_setting_lookup_int(figura_actual, "TiempoInicio", &tiempoInicio);
        config_setting_lookup_int(figura_actual, "TiempoIntervalo", &tiempoIntervalo);
         config_setting_lookup_int(figura_actual, "TiempoVida", &tiempoVida);
        config_setting_lookup_int(figura_actual, "TipoScheduler", &tipoScheduler);
        config_setting_lookup_int(figura_actual, "Tiquetes", &tiquetes);
        
        pFigura* fig = figura_create(n,xInit,yInit,rotacion,colorIn,colorOut,1,tiempoIntervalo,xIncremento,yIncremento,xDir,yDir,xFinal,yFinal,tiempoVida,asignarMonitor(xInit),tiempoInicio,animacion);
        agregarFiguraLista(fig);
        my_thread_create(pintame, 1, (void*) fig, tipoScheduler, tiquetes);

    }
    config_destroy(cf);

    /*
    //pFigura* fig1 = figura_create(1, 0, 0, 0, 1, 2, 1, 100, 1, 0, 1, 1, 90, 0, 45000, asignarMonitor(0), 0, 1);
    //pFigura* fig2 = figura_create(2, 40, 0, 0, 5, 6, 1, 1000, 1, 0, 1, 1, 80, 0, 45000, asignarMonitor(40), 0, 1);
    //pFigura* fig3 = figura_create(3, 0, 8, 0, 3, 4, 1, 500, 1, 0, 1, 1, 80, 8, 40000, asignarMonitor(0), 5000, 0);
    //pFigura* fig4 = figura_create(4, 120, 8, 0, 6, 7, 1, 700, 1, 0, -1, 1, 0, 8, 60000, asignarMonitor(120), 2000, 0);
    agregarFiguraLista(fig1);
    agregarFiguraLista(fig2);
    //agregarFiguraLista(fig3);
    //agregarFiguraLista(fig4);

    my_thread_create(pintame, 1, (void*) fig1, 1, 0);
    my_thread_create(pintame, 1, (void*) fig2, 1, 0);
    //my_thread_create(pintame, 1, (void*) fig3, 1, 0);
    //my_thread_create(pintame, 1, (void*) fig4, 1, 0);
    */

    while (1);
    //my_thread_join(t3);


    printf("Exit\n");
    exit(0);
}
Пример #18
0
void *issueAdd(void *arg) {

	int     mysocfd = (int) arg;

	struct betaler_keywords_visninger_format {
		int kid;
		int betaler_side_id;
	};

	struct betaler_keywords_visninger_format betaler_keywords_visninger[10];
	char buff[1024];
	struct timeval globalstart_time, globalend_time;
	unsigned int addid;
        char *strpointer;
	int siderType_ppctopNr,siderType_ppcsideNr;
	
	struct queryNodeHederFormat queryNodeHeder;
	char queryEscaped[MaxQueryLen*2+1];
	char ppcprovider[32];

	int i,n, y, net_status, showabal;;

	//sjekker vårt egent anonsesystem

	char mysql_query [2048];

	static MYSQL demo_db;


        MYSQL_RES *mysqlres; /* To be used to fetch information into */
        MYSQL_ROW mysqlrow;


	struct SiderHederFormat SiderHeder;
	struct ppcPagesFormat ppcPages[10];

	struct SiderFormat *Sider;

	gettimeofday(&globalstart_time, NULL);

	
        if ((i=recv(mysocfd, &queryNodeHeder, sizeof(queryNodeHeder),MSG_WAITALL)) == -1) {
                perror("recv");
        }

	printf("Query %s\n",queryNodeHeder.query);

	Sider  = (struct SiderFormat *)malloc(sizeof(struct SiderFormat) * (queryNodeHeder.MaxsHits));

        //setter alle sidene som sletett
        for (i=0;i<queryNodeHeder.MaxsHits;i++) {
                Sider[i].deletet = 1;
        }

        //sender svar med en gang at vi kan gjøre dette
        net_status = net_CanDo;
        if ((n=sendall(mysocfd,&net_status, sizeof(net_status))) != sizeof(net_status)) {
                printf("send only %i of %i\n",n,sizeof(net_status));
                perror("sendall net_status");
        }



        /********************************************************************************************/
        #ifdef DEBUG
                printf("sending query to ppc db\n");
        #endif


        mysql_init(&demo_db);

	#ifdef WITH_THREAD
		my_thread_init(); // kalt mysql_thread_init() i mysql 5.0
	#endif




        //if(!mysql_real_connect(&demo_db, "www2.boitho.com", "boitho_remote", "G7J7v5L5Y7", "boitho", 3306, NULL, 0)){
        if(!mysql_real_connect(&demo_db, "localhost", "boitho", "G7J7v5L5Y7", "boithoweb", 3306, NULL, 0)){
                printf(mysql_error(&demo_db));
                //return(1);
		pthread_exit((void *)1); /* exit with status */
        }

        //escaper queryet rikit
        mysql_real_escape_string(&demo_db,queryEscaped,queryNodeHeder.query,strlen(queryNodeHeder.query));

        sprintf(mysql_query, "select tittel,url,beskrivelse,betaler_sider.bruker_navn,betaler_keywords.betaler,betaler_keywords.kid,betaler_sider.id from betaler_keywords,betaler_sider where betaler_keywords.keyword ='%s' and betaler_keywords.betaler_side_id=betaler_sider.id order by betaler desc",queryEscaped);


        if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */
             	printf(mysql_error(&demo_db));
             	//return(1);
		pthread_exit((void *)1); /* exit with status */
        }
        #ifdef DEBUG
                printf("sending query to ppc db end\n");
        #endif

        /********************************************************************************************/


	SiderHeder.TotaltTreff = 0;
	int nrOfppcPages = 0;
	int nrOfBoithoAds = 0;
        //printer ut eventuelt ppc ord
        mysqlres=mysql_store_result(&demo_db); /* Download result from server */
        while ((mysqlrow=mysql_fetch_row(mysqlres)) != NULL) { /* Get a row from the results */
                        //printf("\t<beskrivelse>%s</beskrivelse>\n",mysqlrow[2]);
			//Sider[showabal].type = siderType_ppctop;

			strncpy(ppcPages[nrOfppcPages].title,mysqlrow[0],sizeof(ppcPages[nrOfppcPages].title));
			strncpy(ppcPages[nrOfppcPages].url,mysqlrow[1],sizeof(ppcPages[nrOfppcPages].url));
			strncpy(ppcPages[nrOfppcPages].uri,mysqlrow[1],sizeof(ppcPages[nrOfppcPages].uri));
			strncpy(ppcPages[nrOfppcPages].description,mysqlrow[2],sizeof(ppcPages[nrOfppcPages].description));
			strncpy(ppcPages[nrOfppcPages].user,mysqlrow[3],sizeof(ppcPages[nrOfppcPages].user));

			ppcPages[nrOfppcPages].thumbnail[0] = '\0';

			ppcPages[nrOfppcPages].bid = atof(mysqlrow[4]);
			ppcPages[nrOfppcPages].keyword_id = atoi(mysqlrow[5]);
			ppcPages[nrOfppcPages].DocID = strtoul(mysqlrow[6], (char **)NULL, 10);

			ppcPages[nrOfppcPages].allrank = 10000;

			#ifdef DEBUG
			printf("aa bid %f\n",ppcPages[nrOfppcPages].bid);
			printf("\tUrl: %s\n",ppcPages[nrOfppcPages].url);
	                printf("\tTitle: %s\n",ppcPages[nrOfppcPages].title);
			printf("keyword_id -%s-\n",mysqlrow[5]);
			#endif

			betaler_keywords_visninger[nrOfBoithoAds].kid = ppcPages[nrOfppcPages].keyword_id;
			betaler_keywords_visninger[nrOfBoithoAds].betaler_side_id = ppcPages[nrOfppcPages].DocID;
		++nrOfppcPages;
		++nrOfBoithoAds;
        }
	mysql_free_result(mysqlres);


	/*********************************/

	printf("contry: %s\n",queryNodeHeder.GeoIPcontry);

	if (strcmp(queryNodeHeder.GeoIPcontry,"NO") == 0) {
		strcpy(ppcprovider,"hent");
		//strcpy(ppcprovider,"revenuepilot");

	}
	else {
		//alle språk
		//strcpy(ppcprovider,"revenuepilot");
		//strcpy(ppcprovider,"searchboss");
	}
	strcpy(ppcprovider,"amazon");

	//temp: skrur av 3p xml feeds
	//getPpcAds(ppcprovider,ppcPages,&nrOfppcPages,&queryNodeHeder);

	//temp: Viser en mindre side da vi får problemer med siste?
	//nrOfppcPages--;

	showabal = 0;        
        for (i=0;i<nrOfppcPages;i++) {


		
		/*********************************************/
		//Sider[showabal].type = siderType_ppcside;
		#ifdef DEBUG
		printf("issue add. keyword_id %i\n",ppcPages[i].keyword_id);
		#endif
        	sprintf(mysql_query, "insert into issuedadds values(%s,'%s','%f','%s',%s,'%s','%s','%s','%s','%s','%s','%s','%i','%i')",
			"NULL",
			queryEscaped,
			ppcPages[i].bid,
			ppcPages[i].uri,
			"NOW()",
			0,
			ppcPages[i].user,
			queryNodeHeder.search_user,
			queryNodeHeder.userip,
			queryNodeHeder.HTTP_ACCEPT_LANGUAGE,
			queryNodeHeder.HTTP_USER_AGENT,
			queryNodeHeder.HTTP_REFERER,
			ppcPages[i].keyword_id,
			ppcPages[i].DocID
			);
        
		
		#ifdef DEBUG
		printf("ppc user %s\naffuser %s\n",Sider[i].user,queryNodeHeder.search_user);
		#endif
        	if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */
        	     	printf("Cant insert into issuedadds: %s\nSql query vas %s\n",mysql_error(&demo_db),mysql_query);
        	     	//return(1);
			pthread_exit((void *)1); /* exit with status */
	        }

		addid = mysql_insert_id(&demo_db);

		#ifdef DEBUG
		printf("addid %u\n",addid);
		#endif
		//sprintf(ppcPages[showabal].uri,"http://search.boitho.com/cgi-bin/addout.cgi?addid=%u&addurl=%s",addid,ppcPages[showabal].url);
		sprintf(ppcPages[showabal].uri,"http://bbh-001.boitho.com/cgi-bin/addout.cgi?addid=%u&addurl=%s",addid,ppcPages[showabal].url);
		
		//strcpy(Sider[i].uri,buff);
		/*********************************************/

			if (strlen(ppcPages[i].title) == (sizeof(ppcPages[i].title) -1)) {
				//strcpy(Sider[showabal].title,"Title to long.");
				
				strncpy(Sider[showabal].title,ppcPages[i].title,sizeof(Sider[showabal].title) -3);
				strcat(Sider[showabal].title,"..");
			}
			else {
				strncpy(Sider[showabal].title,ppcPages[i].title,sizeof(Sider[showabal].title));
			}


			strncpy(Sider[showabal].description,ppcPages[i].description,sizeof(Sider[showabal].description));
                        
			strncpy(Sider[showabal].url,ppcPages[i].url,sizeof(Sider[showabal].url));
			strncpy(Sider[showabal].uri,ppcPages[i].uri,sizeof(Sider[showabal].uri));
			strncpy(Sider[showabal].user,ppcPages[i].user,sizeof(Sider[showabal].user));
                        
			strscpy(Sider[showabal].domain,ppcPages[i].domain,sizeof(Sider[showabal].domain));
			
			strscpy(Sider[showabal].thumbnale,ppcPages[i].thumbnail,sizeof(Sider[showabal].thumbnale));

			Sider[showabal].thumbnailwidth = atol(ppcPages[i].thumbnailwidth);
			Sider[showabal].thumbnailheight = atol(ppcPages[i].thumbnailheight);
			
			Sider[showabal].bid = ppcPages[i].bid;

			Sider[showabal].iindex.allrank = ppcPages[i].allrank;


			#ifdef DEBUG
                        printf("%s\t%s\t%f\n",Sider[showabal].url,Sider[showabal].title,ppcPages[i].bid);
              		#endif
			

		++showabal;

        }

	/*********************************/
	siderType_ppctopNr = 0;
	siderType_ppcsideNr = 0;

        for(i=0;i<showabal;i++) {

			#ifdef DEBUG
			printf("uri %s\n",Sider[i].uri);
			#endif

			Sider[i].DocumentIndex.crc32 = crc32boitho(Sider[i].description);
                        Sider[i].deletet = 0;





		//lager fin beskrivlse som slutter på .. isteden får bare et kappet ord, hvis beskrivlese er for lang                
                if (strlen(Sider[i].description) >= 250) {
                	//søker oss til siste space , eller ; og avslutter der
                        if ((strpointer = (char *)strrchr(Sider[i].description,' ')) != NULL) {
                        	strpointer[0] = '\0';
                        }
                        else if ((strpointer = (char *)strrchr(Sider[i].description,';')) != NULL) {
                        	++strpointer; //pekeren peker på semikolonet. SKal ha det med, så må legge il en
                                strpointer[0] = '\0';
                        }
                        strncat(Sider[i].description,"..",2);
            	}
               	
		//hiliter ordet
		sprintf(buff,"<b>%s</b>",queryNodeHeder.query);
		strcasesandr(Sider[i].description,sizeof(Sider[i].description),queryNodeHeder.query,buff);

		//bestemmer ppc type
		//Sider[showabal].type = siderType_ppcside
		//Sider[i].type = siderType_ppctop;
		if ((siderType_ppctopNr < 2) && (strcasestr(Sider[i].description,queryNodeHeder.query) != 0)) {
			Sider[i].type = siderType_ppctop;
			++siderType_ppctopNr;
		}
		else {
			Sider[i].type = siderType_ppcside;
			++siderType_ppcsideNr;
		}

	}	

	//legger datane in i mysql database.
        for(i=0;i<showabal;i++) {


	}


	gettimeofday(&globalend_time, NULL);
	SiderHeder.total_usecs = getTimeDifference(&globalstart_time,&globalend_time);

	SiderHeder.TotaltTreff = showabal;
	SiderHeder.showabal = showabal;
	SiderHeder.filtered = 0;
	SiderHeder.hiliteQuery[0] = '\0';
	sprintf(SiderHeder.servername,"adserver.boitho.com");

	//SiderHeder.queryTime = 0;

        if ((n=sendall(mysocfd,&SiderHeder, sizeof(SiderHeder))) != sizeof(SiderHeder)) {
                printf("send only %i of %i\n",n,sizeof(SiderHeder));
                perror("sendall SiderHeder");
        }

        for(i=0;i<SiderHeder.showabal;i++) {
        //for (i=0;i<queryNodeHeder.MaxsHits;i++) {
		#ifdef DEBUG
                       printf("sending %s, deletet %i\n",Sider[i].url,Sider[i].deletet);
                       printf("bb: -%s-\n",Sider[i].title);
                       printf("url: -%s-\n",Sider[i].url);
			
		#endif

                //if (!Sider[i].deletet) {
                        if ((n=sendall(mysocfd,&Sider[i], sizeof(struct SiderFormat))) != sizeof(struct SiderFormat)) {
                                printf("send only %i of %i\n",n,sizeof(struct SiderFormat));
                                perror("sendall");
                        }

                //}
        }

	//logger alle visningene vi har hatt på egen ppc ord
	for (i=0;i<nrOfBoithoAds;i++) {
		sprintf(mysql_query, "insert DELAYED into betaler_keywords_visninger values(NULL,'%i','%i',NOW())",betaler_keywords_visninger[i].kid,betaler_keywords_visninger[i].betaler_side_id);


	        if(mysql_real_query(&demo_db, mysql_query, strlen(mysql_query))){ /* Make query */
	             	printf(mysql_error(&demo_db));
	             	//return(1);
			pthread_exit((void *)0); /* exit with status */
	        }
		
	}


        mysql_close(&demo_db);

        //close(mysocfd);


	free(Sider);

	close(mysocfd);

 	#ifdef WITH_THREAD
		my_thread_end(); // kalt mysql_thread_end() i mysql 5.0
            	pthread_exit((void *)0); /* exit with status */
        #endif

	printf("end\n");
       

	//return 0;
}
Пример #19
0
my_bool my_thread_global_init(void)
{
  int pth_ret;

  if (my_thread_global_init_done)
    return 0;
  my_thread_global_init_done= 1;

#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
  /*
    Set mutex type to "fast" a.k.a "adaptive"

    In this case the thread may steal the mutex from some other thread
    that is waiting for the same mutex.  This will save us some
    context switches but may cause a thread to 'starve forever' while
    waiting for the mutex (not likely if the code within the mutex is
    short).
  */
  pthread_mutexattr_init(&my_fast_mutexattr);
  pthread_mutexattr_settype(&my_fast_mutexattr,
                            PTHREAD_MUTEX_ADAPTIVE_NP);
#endif

#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
  /*
    Set mutex type to "errorcheck"
  */
  pthread_mutexattr_init(&my_errorcheck_mutexattr);
  pthread_mutexattr_settype(&my_errorcheck_mutexattr,
                            PTHREAD_MUTEX_ERRORCHECK);
#endif

  DBUG_ASSERT(! THR_KEY_mysys_initialized);
  if ((pth_ret= my_create_thread_local_key(&THR_KEY_mysys, NULL)) != 0)
  { /* purecov: begin inspected */
    my_message_local(ERROR_LEVEL, "Can't initialize threads: error %d",
                     pth_ret);
    /* purecov: end */
    return 1;
  }

  THR_KEY_mysys_initialized= TRUE;
  mysql_mutex_init(key_THR_LOCK_malloc, &THR_LOCK_malloc, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_THR_LOCK_open, &THR_LOCK_open, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_THR_LOCK_charset, &THR_LOCK_charset, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_THR_LOCK_threads, &THR_LOCK_threads, MY_MUTEX_INIT_FAST);

  if (my_thread_init())
    return 1;

  mysql_mutex_init(key_THR_LOCK_lock, &THR_LOCK_lock, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_THR_LOCK_myisam, &THR_LOCK_myisam, MY_MUTEX_INIT_SLOW);
  mysql_mutex_init(key_THR_LOCK_myisam_mmap, &THR_LOCK_myisam_mmap, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_THR_LOCK_heap, &THR_LOCK_heap, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_THR_LOCK_net, &THR_LOCK_net, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_THR_COND_threads, &THR_COND_threads);

#ifdef _MSC_VER
  install_sigabrt_handler();
#endif

  return 0;
}
Пример #20
0
int thread_main (thread_arg* arg)
{
  int t_num= arg->number;
  int port= arg->port;
  int r,i;
  char *connect_string = connect_strings[t_num % count_connect_strings];

  printf("thread (%d) started.\n", t_num);

  char *db_string_ptr;
  MYSQL* resp;

  db_string_ptr = db_string;

  /* EXEC SQL WHENEVER SQLERROR GOTO sqlerr;*/

  if(num_node > 0){ /* RAC mode */
    db_string_ptr = node_string[((num_node * t_num)/num_conn)];
  }

  my_thread_init();
  if(is_local==1){
    /* exec sql connect :connect_string; */
    resp = mysql_real_connect(ctx[t_num], "localhost", db_user, db_password, db_string, 0, db_socket, 0);
  }else{
    /* exec sql connect :connect_string USING :db_string; */
    resp = mysql_real_connect(ctx[t_num], connect_string, db_user, db_password, db_string, port, NULL, 0);
  }

  if(resp) {
    mysql_autocommit(ctx[t_num], 0);
  } else {
    mysql_close(ctx[t_num]);
    goto sqlerr;
  }

  for(i=0;i<40;i++){
      stmt[t_num][i] = mysql_stmt_init(ctx[t_num]);
      if(!stmt[t_num][i]) goto sqlerr;
  }

  /* Prepare ALL of SQLs */
  if( mysql_stmt_prepare(stmt[t_num][0], "SELECT c_discount, c_last, c_credit, w_tax FROM customer, warehouse WHERE w_id = ? AND c_w_id = w_id AND c_d_id = ? AND c_id = ?", 128) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][1], "SELECT d_next_o_id, d_tax FROM district WHERE d_id = ? AND d_w_id = ? FOR UPDATE", 80) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][2], "UPDATE district SET d_next_o_id = ? + 1 WHERE d_id = ? AND d_w_id = ?", 69) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][3], "INSERT INTO orders (o_id, o_d_id, o_w_id, o_c_id, o_entry_d, o_ol_cnt, o_all_local) VALUES(?, ?, ?, ?, ?, ?, ?)", 111) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][4], "INSERT INTO new_orders (no_o_id, no_d_id, no_w_id) VALUES (?,?,?)", 65) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][5], "SELECT i_price, i_name, i_data FROM item WHERE i_id = ?", 55) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][6], "SELECT s_quantity, s_data, s_dist_01, s_dist_02, s_dist_03, s_dist_04, s_dist_05, s_dist_06, s_dist_07, s_dist_08, s_dist_09, s_dist_10 FROM stock WHERE s_i_id = ? AND s_w_id = ? FOR UPDATE", 189) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][7], "UPDATE stock SET s_quantity = ? WHERE s_i_id = ? AND s_w_id = ?", 63) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][8], "INSERT INTO order_line (ol_o_id, ol_d_id, ol_w_id, ol_number, ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_dist_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", 159) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][9], "UPDATE warehouse SET w_ytd = w_ytd + ? WHERE w_id = ?", 53) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][10], "SELECT w_street_1, w_street_2, w_city, w_state, w_zip, w_name FROM warehouse WHERE w_id = ?", 91) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][11], "UPDATE district SET d_ytd = d_ytd + ? WHERE d_w_id = ? AND d_id = ?", 67) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][12], "SELECT d_street_1, d_street_2, d_city, d_state, d_zip, d_name FROM district WHERE d_w_id = ? AND d_id = ?", 105) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][13], "SELECT count(c_id) FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ?", 79) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][14], "SELECT c_id FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ? ORDER BY c_first", 89) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][15], "SELECT c_first, c_middle, c_last, c_street_1, c_street_2, c_city, c_state, c_zip, c_phone, c_credit, c_credit_lim, c_discount, c_balance, c_since FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_id = ? FOR UPDATE", 215) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][16], "SELECT c_data FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 72) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][17], "UPDATE customer SET c_balance = ?, c_data = ? WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 90) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][18], "UPDATE customer SET c_balance = ? WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 78) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][19], "INSERT INTO history(h_c_d_id, h_c_w_id, h_c_id, h_d_id, h_w_id, h_date, h_amount, h_data) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", 120) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][20], "SELECT count(c_id) FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ?", 79) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][21], "SELECT c_balance, c_first, c_middle, c_last FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_last = ? ORDER BY c_first", 121) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][22], "SELECT c_balance, c_first, c_middle, c_last FROM customer WHERE c_w_id = ? AND c_d_id = ? AND c_id = ?", 102) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][23], "SELECT o_id, o_entry_d, COALESCE(o_carrier_id,0) FROM orders WHERE o_w_id = ? AND o_d_id = ? AND o_c_id = ? AND o_id = (SELECT MAX(o_id) FROM orders WHERE o_w_id = ? AND o_d_id = ? AND o_c_id = ?)", 196) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][24], "SELECT ol_i_id, ol_supply_w_id, ol_quantity, ol_amount, ol_delivery_d FROM order_line WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id = ?", 135) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][25], "SELECT COALESCE(MIN(no_o_id),0) FROM new_orders WHERE no_d_id = ? AND no_w_id = ?", 81) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][26], "DELETE FROM new_orders WHERE no_o_id = ? AND no_d_id = ? AND no_w_id = ?", 72) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][27], "SELECT o_c_id FROM orders WHERE o_id = ? AND o_d_id = ? AND o_w_id = ?", 70) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][28], "UPDATE orders SET o_carrier_id = ? WHERE o_id = ? AND o_d_id = ? AND o_w_id = ?", 79) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][29], "UPDATE order_line SET ol_delivery_d = ? WHERE ol_o_id = ? AND ol_d_id = ? AND ol_w_id = ?", 89) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][30], "SELECT SUM(ol_amount) FROM order_line WHERE ol_o_id = ? AND ol_d_id = ? AND ol_w_id = ?", 87) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][31], "UPDATE customer SET c_balance = c_balance + ? , c_delivery_cnt = c_delivery_cnt + 1 WHERE c_id = ? AND c_d_id = ? AND c_w_id = ?", 128) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][32], "SELECT d_next_o_id FROM district WHERE d_id = ? AND d_w_id = ?", 62) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][33], "SELECT DISTINCT ol_i_id FROM order_line WHERE ol_w_id = ? AND ol_d_id = ? AND ol_o_id < ? AND ol_o_id >= (? - 20)", 113) ) goto sqlerr;
  if( mysql_stmt_prepare(stmt[t_num][34], "SELECT count(*) FROM stock WHERE s_w_id = ? AND s_i_id = ? AND s_quantity < ?", 77) ) goto sqlerr;

  r = driver(t_num);

  /* EXEC SQL COMMIT WORK; */
  if( mysql_commit(ctx[t_num]) ) goto sqlerr;

  for(i=0;i<40;i++){
      mysql_stmt_free_result(stmt[t_num][i]);
      mysql_stmt_close(stmt[t_num][i]);
  }

  /* EXEC SQL DISCONNECT; */
  mysql_close(ctx[t_num]);

  printf(".");
  fflush(stdout);

  return(r);

 sqlerr:
  fprintf(stdout, "error at thread_main\n");
  error(ctx[t_num],0);
  return(0);

}
Пример #21
0
void *poller(void *thread_args)
{
    worker_t *worker = (worker_t *) thread_args;
    crew_t *crew = worker->crew;
    target_t *entry = NULL;
    void *sessp = NULL;
    struct snmp_session session;
    struct snmp_pdu *pdu = NULL;
    struct snmp_pdu *response = NULL;
    oid anOID[MAX_OID_LEN];
    size_t anOID_len = MAX_OID_LEN;
    struct variable_list *vars = NULL;
    unsigned long long result = 0;
    unsigned long long last_value = 0;
    unsigned long long insert_val = 0;
    int status = 0, bits = 0, init = 0;
    char query[BUFSIZE];
    char storedoid[BUFSIZE];
    char result_string[BUFSIZE];

    if (set.verbose >= HIGH)
	printf("Thread [%d] starting.\n", worker->index);
    if (MYSQL_VERSION_ID > 40000)
       mysql_thread_init();
    else 
       my_thread_init();

    while (1) {
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] locking (wait on work)\n", worker->index);

	PT_MUTEX_LOCK(&crew->mutex);

	while (current == NULL) {
		PT_COND_WAIT(&crew->go, &crew->mutex);
	}
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] done waiting, received go (work cnt: %d)\n", worker->index, crew->work_count);

	if (current != NULL) {
	    if (set.verbose >= HIGH)
	      printf("Thread [%d] processing %s %s (%d work units remain in queue)\n", worker->index, current->host, current->objoid, crew->work_count);
	    snmp_sess_init(&session);
		if (set.snmp_ver == 2)
	      session.version = SNMP_VERSION_2c;
		else
	      session.version = SNMP_VERSION_1;
	    session.peername = current->host;
		session.remote_port = set.snmp_port;
	    session.community = current->community;
	    session.community_len = strlen(session.community);

	    sessp = snmp_sess_open(&session);
	    anOID_len = MAX_OID_LEN;
	    pdu = snmp_pdu_create(SNMP_MSG_GET);
	    read_objid(current->objoid, anOID, &anOID_len);
	    entry = current;
	    last_value = current->last_value;
	    init = current->init;
	    insert_val = 0;
	    bits = current->bits;
	    strncpy(storedoid, current->objoid, sizeof(storedoid));
		current = getNext();
	}
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] unlocking (done grabbing current)\n", worker->index);
	PT_MUTEX_UNLOCK(&crew->mutex);
	snmp_add_null_var(pdu, anOID, anOID_len);
	if (sessp != NULL) 
	   status = snmp_sess_synch_response(sessp, pdu, &response);
	else
	   status = STAT_DESCRIP_ERROR;

	/* Collect response and process stats */
	PT_MUTEX_LOCK(&stats.mutex);
	if (status == STAT_DESCRIP_ERROR) {
	    stats.errors++;
            printf("*** SNMP Error: (%s) Bad descriptor.\n", session.peername);
	} else if (status == STAT_TIMEOUT) {
	    stats.no_resp++;
	    printf("*** SNMP No response: (%s@%s).\n", session.peername,
	       storedoid);
	} else if (status != STAT_SUCCESS) {
	    stats.errors++;
	    printf("*** SNMP Error: (%s@%s) Unsuccessuful (%d).\n", session.peername,
	       storedoid, status);
	} else if (status == STAT_SUCCESS && response->errstat != SNMP_ERR_NOERROR) {
	    stats.errors++;
	    printf("*** SNMP Error: (%s@%s) %s\n", session.peername,
	       storedoid, snmp_errstring(response->errstat));
	} else if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
	    stats.polls++;
	} 
	PT_MUTEX_UNLOCK(&stats.mutex);

	/* Liftoff, successful poll, process it */
	if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {
	    vars = response->variables;
#ifdef OLD_UCD_SNMP
            sprint_value(result_string, anOID, anOID_len, vars);
#else
	    snprint_value(result_string, BUFSIZE, anOID, anOID_len, vars);
#endif
	    switch (vars->type) {
		/*
		 * Switch over vars->type and modify/assign result accordingly.
		 */
		case ASN_COUNTER64:
		    if (set.verbose >= DEBUG) printf("64-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = vars->val.counter64->high;
		    result = result << 32;
		    result = result + vars->val.counter64->low;
		    break;
		case ASN_COUNTER:
		    if (set.verbose >= DEBUG) printf("32-bit result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_INTEGER:
		    if (set.verbose >= DEBUG) printf("Integer result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_GAUGE:
		    if (set.verbose >= DEBUG) printf("32-bit gauge: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_TIMETICKS:
		    if (set.verbose >= DEBUG) printf("Timeticks result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		case ASN_OPAQUE:
		    if (set.verbose >= DEBUG) printf("Opaque result: (%s@%s) %s\n", session.peername, storedoid, result_string);
		    result = (unsigned long) *(vars->val.integer);
		    break;
		default:
		    if (set.verbose >= DEBUG) printf("Unknown result type: (%s@%s) %s\n", session.peername, storedoid, result_string);
	    }

		/* Gauge Type */
		if (bits == 0) {
			if (result != last_value) {
				insert_val = result;
				if (set.verbose >= HIGH)
					printf("Thread [%d]: Gauge change from %lld to %lld\n", worker->index, last_value, insert_val);
			} else {
				if (set.withzeros) 
					insert_val = result;
				if (set.verbose >= HIGH)
					printf("Thread [%d]: Gauge steady at %lld\n", worker->index, insert_val);
			}
	    /* Counter Wrap Condition */
	    } else if (result < last_value) {
			PT_MUTEX_LOCK(&stats.mutex);
              stats.wraps++;
			PT_MUTEX_UNLOCK(&stats.mutex);
	      if (bits == 32) insert_val = (THIRTYTWO - last_value) + result;
	      else if (bits == 64) insert_val = (SIXTYFOUR - last_value) + result;
	      if (set.verbose >= LOW) {
	         printf("*** Counter Wrap (%s@%s) [poll: %llu][last: %llu][insert: %llu]\n",
	         session.peername, storedoid, result, last_value, insert_val);
	      }
	    /* Not a counter wrap and this is not the first poll */
	    } else if ((last_value >= 0) && (init != NEW)) {
		insert_val = result - last_value;
	        /* Print out SNMP result if verbose */
	        if (set.verbose == DEBUG)
		  printf("Thread [%d]: (%lld-%lld) = %llu\n", worker->index, result, last_value, insert_val);
	        if (set.verbose == HIGH)
		  printf("Thread [%d]: %llu\n", worker->index, insert_val);
            /* last_value < 0, so this must be the first poll */
	    } else {
                if (set.verbose >= HIGH) printf("Thread [%d]: First Poll, Normalizing\n", worker->index);
	    }

		/* Check for bogus data, either negative or unrealistic */
	    if (insert_val > entry->maxspeed || result < 0) {
			if (set.verbose >= LOW) printf("*** Out of Range (%s@%s) [insert_val: %llu] [oor: %lld]\n",
				session.peername, storedoid, insert_val, entry->maxspeed);
			insert_val = 0;
			PT_MUTEX_LOCK(&stats.mutex);
			stats.out_of_range++;
			PT_MUTEX_UNLOCK(&stats.mutex);
	    }

		if (!(set.dboff)) {
			if ( (insert_val > 0) || (set.withzeros) ) {
				PT_MUTEX_LOCK(&crew->mutex);
				snprintf(query, sizeof(query), "INSERT INTO %s VALUES (%d, NOW(), %llu)",
					entry->table, entry->iid, insert_val);
				if (set.verbose >= DEBUG) printf("SQL: %s\n", query);
				status = mysql_query(&mysql, query);
				if (status) printf("*** MySQL Error: %s\n", mysql_error(&mysql));
				PT_MUTEX_UNLOCK(&crew->mutex);

				if (!status) {
					PT_MUTEX_LOCK(&stats.mutex);
					stats.db_inserts++;
					PT_MUTEX_UNLOCK(&stats.mutex);
				} 
			} /* insert_val > 0 or withzeros */	
		} /* !dboff */

	} /* STAT_SUCCESS */

        if (sessp != NULL) {
           snmp_sess_close(sessp);
           if (response != NULL) snmp_free_pdu(response);
        }

	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] locking (update work_count)\n", worker->index);
	PT_MUTEX_LOCK(&crew->mutex);
	crew->work_count--;
	/* Only if we received a positive result back do we update the
	   last_value object */
	if (status == STAT_SUCCESS) entry->last_value = result;
	if (init == NEW) entry->init = LIVE;
	if (crew->work_count <= 0) {
	    if (set.verbose >= HIGH) printf("Queue processed. Broadcasting thread done condition.\n");
		PT_COND_BROAD(&crew->done);
	}
	if (set.verbose >= DEVELOP)
	    printf("Thread [%d] unlocking (update work_count)\n", worker->index);

		PT_MUTEX_UNLOCK(&crew->mutex);
    }				/* while(1) */
}
Пример #22
0
/*
  stress test: wait on a random number of random threads.
  it always succeeds (unless crashes or hangs).
*/
pthread_handler_t test_wt(void *arg)
{
  int    m, n, i, id, res;
  struct my_rnd_struct rand;

  my_thread_init();

  mysql_mutex_lock(&mutex);
  id= cnt++;
  wt_thd_lazy_init(& thds[id].thd,
                   & wt_deadlock_search_depth_short, & wt_timeout_short,
                   & wt_deadlock_search_depth_long, & wt_timeout_long);

  /* now, wait for everybody to be ready to run */
  if (cnt >= THREADS)
    mysql_cond_broadcast(&thread_sync);
  else
    while (cnt < THREADS)
      mysql_cond_wait(&thread_sync, &mutex);
  mysql_mutex_unlock(&mutex);

  my_rnd_init(&rand, (ulong)(intptr)&m, id);
  if (kill_strategy == YOUNGEST)
    thds[id].thd.weight= (ulong)~my_getsystime();
  if (kill_strategy == LOCKS)
    thds[id].thd.weight= 0;

  for (m= *(int *)arg; m ; m--)
  {
    WT_RESOURCE_ID resid;
    int blockers[THREADS/10], j, k;

    resid.value= id;
    resid.type= &restype;

    res= 0;

    /* prepare for waiting for a random number of random threads */
    for (j= n= (rnd() % THREADS)/10; !res && j >= 0; j--)
    {
retry:
      i= rnd() % (THREADS-1); /* pick a random thread */
      if (i >= id) i++;   /* with a number from 0 to THREADS-1 excluding ours */

      for (k=n; k >=j; k--) /* the one we didn't pick before */
        if (blockers[k] == i)
          goto retry;
      blockers[j]= i;

      if (kill_strategy == RANDOM)
        thds[id].thd.weight= rnd();

      mysql_mutex_lock(& thds[i].lock);
      res= wt_thd_will_wait_for(& thds[id].thd, & thds[i].thd, &resid);
      mysql_mutex_unlock(& thds[i].lock);
    }

    if (!res)
    {
      mysql_mutex_lock(&lock);
      res= wt_thd_cond_timedwait(& thds[id].thd, &lock);
      mysql_mutex_unlock(&lock);
    }

    if (res)
    {
      mysql_mutex_lock(& thds[id].lock);
      mysql_mutex_lock(&lock);
      wt_thd_release_all(& thds[id].thd);
      mysql_mutex_unlock(&lock);
      mysql_mutex_unlock(& thds[id].lock);
      if (kill_strategy == LOCKS)
        thds[id].thd.weight= 0;
      if (kill_strategy == YOUNGEST)
        thds[id].thd.weight= (ulong)~my_getsystime();
    }
    else if (kill_strategy == LOCKS)
      thds[id].thd.weight++;
  }

  mysql_mutex_lock(&mutex);
  /* wait for everybody to finish */
  if (!--cnt)
    mysql_cond_broadcast(&thread_sync);
  else
    while (cnt)
      mysql_cond_wait(&thread_sync, &mutex);

  mysql_mutex_lock(& thds[id].lock);
  mysql_mutex_lock(&lock);
  wt_thd_release_all(& thds[id].thd);
  mysql_mutex_unlock(&lock);
  mysql_mutex_unlock(& thds[id].lock);
  wt_thd_destroy(& thds[id].thd);

  if (!--running_threads) /* now, signal when everybody is done with deinit */
    mysql_cond_signal(&cond);
  mysql_mutex_unlock(&mutex);
  DBUG_PRINT("wt", ("exiting"));
  my_thread_end();
  return 0;
}