Пример #1
0
/**
 * @short Generates a new response object
 * @memberof onion_response_t
 *
 * This response is generated from a request, and gets from there the writer and writer data.
 *
 * Also fills some important data, as server Id, License type, and the default content type.
 *
 * Default content type is HTML, as normally this is what is needed. This is nontheless just
 * the default, and can be changed to any other with a call to:
 *
 *   onion_response_set_header(res, "Content-Type", my_type);
 *
 * The response object must be freed with onion_response_free, which also returns the keep alive
 * status.
 *
 * onion_response objects are passed by onion internally to process the request, and should not be
 * created by user normally. Nontheless the option exist.
 *
 * @returns An onion_response object for that request.
 */
onion_response *onion_response_new(onion_request *req){
	onion_response *res=onion_low_malloc(sizeof(onion_response));

	res->request=req;
	res->headers=onion_dict_new();
	res->code=200; // The most normal code, so no need to overwrite it in other codes.
	res->flags=0;
	res->sent_bytes_total=res->length=res->sent_bytes=0;
	res->buffer_pos=0;

#ifndef DONT_USE_DATE_HEADER
	{
		time_t t;
		struct tm *tmp;

		t = time(NULL);

		// onion_response_last_date_header is set to t later. It should be more or less atomic.
		// If not no big deal, as we will just use slightly more CPU on those "ephemeral" moments.

		if (t!=onion_response_last_time){
			ONION_DEBUG("Recalculating date header");
			char current_datetime[200];

			tmp = localtime(&t);
			if (tmp == NULL) {
					perror("localtime");
					exit(EXIT_FAILURE);
			}

			if (strftime(current_datetime, sizeof(current_datetime), "%a, %d %b %Y %H:%M:%S %Z", tmp) == 0) {
					fprintf(stderr, "strftime returned 0");
					exit(EXIT_FAILURE);
			}
			// Risky, not using mutex...
#ifdef HAVE_PTHREAD
			pthread_rwlock_wrlock(&onion_response_date_lock);
#endif
			onion_response_last_time=t;
			if (onion_response_last_date_header)
				onion_low_free(onion_response_last_date_header);
			onion_response_last_date_header=onion_low_strdup(current_datetime);
#ifdef HAVE_PTHREAD
			pthread_rwlock_unlock(&onion_response_date_lock);
#endif
		}
	}
#ifdef HAVE_PTHREAD
	pthread_rwlock_rdlock(&onion_response_date_lock);
#endif
	assert(onion_response_last_date_header);
	onion_dict_add(res->headers, "Date", onion_response_last_date_header, OD_DUP_VALUE);
#ifdef HAVE_PTHREAD
	pthread_rwlock_unlock(&onion_response_date_lock);
#endif
#endif // USE_DATE_HEADER
	// Sorry for the advertisment.
	onion_dict_add(res->headers, "Server", "libonion v" ONION_VERSION " - coralbits.com", 0);
	onion_dict_add(res->headers, "Content-Type", "text/html", 0); // Maybe not the best guess, but really useful.
	//time_t t=time(NULL);
	//onion_dict_add(res->headers, "Date", asctime(localtime(&t)), OD_DUP_VALUE);

	return res;
}
Пример #2
0
int pfring_mod_recv(pfring *ring, u_char** buffer, u_int buffer_len,
		    struct pfring_pkthdr *hdr,
		    u_int8_t wait_for_incoming_packet) {
  int rc = 0;

  if(ring->is_shutting_down || (ring->buffer == NULL))
    return(-1);

  ring->break_recv_loop = 0;

  do_pfring_recv:
    if(ring->break_recv_loop)
      return(0);

    if(unlikely(ring->reentrant))
      pthread_rwlock_wrlock(&ring->rx_lock);

    //rmb();

    if(pfring_there_is_pkt_available(ring)) {
      char *bucket = &ring->slots[ring->slots_info->remove_off];
      u_int32_t next_off, real_slot_len, bktLen;

      /* Keep it for packet sending */
      ring->tx.last_received_hdr = (struct pfring_pkthdr*)bucket;

      memcpy(hdr, bucket, ring->slot_header_len);

      //if((hdr->caplen > 1518) || (hdr->len > 1518)) 
      //  fprintf(stderr, "%s:%d-----> Invalid packet length [caplen: %u][len: %u]"
      //                  "[hdr len: %u][slot len: %u][real slot len: %u]"
      //                  "[insert_off: %u][remove_off: %u][tot_insert: %lu][tot_read: %lu]\n", 
      //          __FUNCTION__, __LINE__, hdr->caplen, hdr->len, ring->slot_header_len, 
      //          ring->slots_info->slot_len, ring->slot_header_len+hdr->caplen, 
      //          ring->slots_info->insert_off, ring->slots_info->remove_off, 
      //          ring->slots_info->tot_insert, ring->slots_info->tot_read);

      if(ring->slot_header_len != sizeof(struct pfring_pkthdr)) /* using short_pkt_header, parsed_header_len is not available */
	bktLen = hdr->caplen;
      else
	bktLen = hdr->caplen + hdr->extended_hdr.parsed_header_len;

      real_slot_len = ring->slot_header_len + bktLen;
      if(bktLen > buffer_len) bktLen = buffer_len;

      if(buffer_len == 0)
	*buffer = (u_char*)&bucket[ring->slot_header_len];
      else
	memcpy(*buffer, &bucket[ring->slot_header_len], bktLen);

      next_off = ring->slots_info->remove_off + real_slot_len;
      if((next_off + ring->slots_info->slot_len) > (ring->slots_info->tot_mem - sizeof(FlowSlotInfo)))
        next_off = 0;
      
#ifdef USE_MB
      /* This prevents the compiler from reordering instructions.
       * http://en.wikipedia.org/wiki/Memory_ordering#Compiler_memory_barrier */
      gcc_mb();
#endif

      ring->slots_info->tot_read++, ring->slots_info->remove_off = next_off;

      /* Ugly safety check */
      if(unlikely((ring->slots_info->tot_insert == ring->slots_info->tot_read)
	 && (ring->slots_info->remove_off > ring->slots_info->insert_off))) {
	ring->slots_info->remove_off = ring->slots_info->insert_off;
        fprintf(stderr, " *** corrupted ring buffer indexes (recovered) ***\n");
      }

      if(unlikely(ring->reentrant)) pthread_rwlock_unlock(&ring->rx_lock);
      return(1);
    }

    /* Nothing to do: we need to wait */
    if(unlikely(ring->reentrant)) pthread_rwlock_unlock(&ring->rx_lock);

    if(wait_for_incoming_packet) {
      rc = pfring_poll(ring, ring->poll_duration);

      if((rc == -1) && (errno != EINTR))
	return(-1);
      else
	goto do_pfring_recv;
    }

  return(0); /* non-blocking, no packet */
}
Пример #3
0
void generate_config(BUFFER *wb, int only_changed)
{
	int i, pri;
	struct config *co;
	struct config_value *cv;

	for(i = 0; i < 3 ;i++) {
		switch(i) {
			case 0:
				buffer_strcat(wb,
					"# NetData Configuration\n"
					"# You can uncomment and change any of the options below.\n"
					"# The value shown in the commented settings, is the default value.\n"
					"\n# global netdata configuration\n");
				break;

			case 1:
				buffer_strcat(wb, "\n\n# per plugin configuration\n");
				break;

			case 2:
				buffer_strcat(wb, "\n\n# per chart configuration\n");
				break;
		}

		pthread_rwlock_wrlock(&config_rwlock);
		for(co = config_root; co ; co = co->next) {
			if(strcmp(co->name, "global") == 0 || strcmp(co->name, "plugins") == 0) pri = 0;
			else if(strncmp(co->name, "plugin:", 7) == 0) pri = 1;
			else pri = 2;

			if(i == pri) {
				int used = 0;
				int changed = 0;
				int count = 0;

				pthread_rwlock_wrlock(&co->rwlock);

				for(cv = co->values; cv ; cv = cv->next) {
					used += (cv->flags && CONFIG_VALUE_USED)?1:0;
					changed += (cv->flags & CONFIG_VALUE_CHANGED)?1:0;
					count++;
				}

				pthread_rwlock_unlock(&co->rwlock);

				if(!count) continue;
				if(only_changed && !changed) continue;

				if(!used) {
					buffer_sprintf(wb, "\n# node '%s' is not used.", co->name);
				}

				buffer_sprintf(wb, "\n[%s]\n", co->name);

				pthread_rwlock_wrlock(&co->rwlock);
				for(cv = co->values; cv ; cv = cv->next) {

					if(used && !(cv->flags & CONFIG_VALUE_USED)) {
						buffer_sprintf(wb, "\n\t# option '%s' is not used.\n", cv->name);
					}
					buffer_sprintf(wb, "\t%s%s = %s\n", ((!(cv->flags & CONFIG_VALUE_CHANGED)) && (cv->flags & CONFIG_VALUE_USED))?"# ":"", cv->name, cv->value);
				}
				pthread_rwlock_unlock(&co->rwlock);
			}
		}
		pthread_rwlock_unlock(&config_rwlock);
	}
}
Пример #4
0
/**
 * @short Do a read lock. Several can lock for reading, but only can be writing.
 * @memberof onion_dict_t
 */
void onion_dict_lock_write(onion_dict *dict){
#ifdef HAVE_PTHREADS
	pthread_rwlock_wrlock(&dict->lock);
#endif
}
void xsltp_rwlock_wrlock(xsltp_rwlock_t *rwlock) {
	if (pthread_rwlock_wrlock(&rwlock->rwlock) != 0) {
		perror("Write lock failed");
	}
}
Пример #6
0
int main()
{
	int cnt = 0;
	pthread_t rd_thread1, rd_thread2;
	
	if(pthread_rwlock_init(&rwlock, NULL) != 0)
	{
		printf("main: Error at pthread_rwlock_init()\n");
		return PTS_UNRESOLVED;
	}

	printf("main: attempt read lock\n");
	if(pthread_rwlock_rdlock(&rwlock) != 0)
	{
		printf("main: Error at pthread_rwlock_rdlock()\n");
		return PTS_UNRESOLVED;
	}
	printf("main: acquired read lock\n");
	
	thread_state = NOT_CREATED_THREAD;
	
	printf("main: create rd_thread1\n");
	if(pthread_create(&rd_thread1, NULL, fn_rd, NULL) != 0)
	{
		printf("main: Error when creating rd_thread1\n");
		return PTS_UNRESOLVED;
	}
	
	/* If the shared data is not altered by child after 5 seconds,
	   we regard it as blocked */

	/* we expect the thread not to block */
	cnt = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 5); 
	
	if(thread_state == ENTERED_THREAD)
	{
		/* the child thread started but blocked */
		printf("Test FAILED: rd_thread1 blocked on pthread_rwlock_timedrdlock()\n");
		exit(PTS_FAIL);
	}
	else if(thread_state != EXITING_THREAD)
	{
		printf("Unexpected thread state %d\n", thread_state);	
		exit(PTS_UNRESOLVED);
	}
		
	if(pthread_join(rd_thread1, NULL) != 0)
	{
		printf("main: Error when join rd_thread1\n");
		exit(PTS_UNRESOLVED);
	}

	printf("main: unlock read lock\n");
	if(pthread_rwlock_unlock(&rwlock) != 0)
	{
		printf("main: Error when release read lock\n");
		return PTS_UNRESOLVED;	
	}
	
	printf("main: attempt write lock\n");
	if(pthread_rwlock_wrlock(&rwlock) != 0)
	{
		printf("main: Failed to get write lock\n");
		return PTS_UNRESOLVED;	
	}
	printf("main: acquired write lock\n");

	thread_state = NOT_CREATED_THREAD;
	printf("main: create rd_thread2\n");
	if(pthread_create(&rd_thread2, NULL, fn_rd, NULL) != 0)
	{
		printf("main: Failed to create rd_thread2\n");
		return PTS_UNRESOLVED;
	}
	
	/* we expect rd_thread2 to block and timeout. */
	cnt = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 5); 
	
	if(thread_state == EXITING_THREAD)
	{
		/* the child thread does not block, check the time interval */
		struct timeval time_diff;
		time_diff.tv_sec = currsec2.tv_sec - currsec1.tv_sec;
		time_diff.tv_usec = currsec2.tv_usec - currsec1.tv_usec;
		if (time_diff.tv_usec < 0)
		{
			--time_diff.tv_sec;
			time_diff.tv_usec += 1000000;
		}
		if(time_diff.tv_sec < TIMEOUT)
		{
			printf("Test FAILED: the timer expired and thread terminated, "
				"but the timeout is not correct: "
				"start time %ld.%06ld, end time %ld.%06ld\n", 
				(long) currsec1.tv_sec, (long) currsec1.tv_usec, 
				(long) currsec2.tv_sec, (long) currsec2.tv_usec);
			exit(PTS_FAIL);
		} else
			printf("thread: read lock correctly timed out\n");
	}
	else if(thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: read block was not terminated even when the timer expired\n");
		exit(PTS_FAIL);
	}
	else
	{
		printf("Unexpected thread state %d\n", thread_state);
		return PTS_UNRESOLVED;
	}

	printf("main: unlock write lock\n");
	if(pthread_rwlock_unlock(&rwlock) != 0)
	{
		printf("main: Failed to release write lock\n");
		exit(PTS_UNRESOLVED);
	}

	if(pthread_rwlock_destroy(&rwlock) != 0)
	{
		printf("Error at pthread_rwlockattr_destroy()\n");
		exit(PTS_UNRESOLVED);
	}	

	printf("Test PASSED\n");
	return PTS_PASS;
}
Пример #7
0
void
vdir_wrlock(struct vdir *vd)
{
	CHECK_OBJ_NOTNULL(vd, VDIR_MAGIC);
	AZ(pthread_rwlock_wrlock(&vd->mtx));
}
Пример #8
0
 int wrlock()
 {
     return pthread_rwlock_wrlock(&rwlock_);
 }
Пример #9
0
int main(int argc, char *argv[]){
    logging_init();
    logmsg(LOG_INFO, "Server started and logging started.");
    int xsize = DEFAULT_X_SIZE;
    int zsize = DEFAULT_Z_SIZE;
    char *filename = NULL;
    char *out_name = NULL;
    for(int i=0; i < argc; i++){
	if (strcmp("-s", argv[i])== 0){
	    xsize = atoi(argv[i+1]);
	    zsize = atoi(argv[i+2]);
	    i += 2;
	} else if (strcmp("-f", argv[i]) == 0){
	    filename = argv[i+1];
	} else if (strcmp("-o", argv[i]) == 0){
	    out_name = argv[i+1];
	}
    }
    
    Map *map;
    if (filename == NULL){
	map = Map_new_air(xsize,zsize);
	Block b;
	b.id = 1;
	b.metadata = 0;
    
	Map_set_below(map, b, 60);
    
	b.id=20; map->chunks[0]->blocks[0] = b; //Debugging

	if (out_name != NULL){
	    filename = out_name;
	}
    } else {
	map = Map_read(filename);
    }
    
    Server *server = Server_create(map, 10);
    sigint_server = server;
    server->is_running = 1;
    server->filename = filename;
    signal(SIGINT, catch_sigint);
    
    pthread_create(&(server->distributor_thread),
		   NULL, &connection_distributor_thread, server);
    
    logmsg(LOG_INFO, "Distributor thread started.");

    struct timespec sleeptime;
    sleeptime.tv_sec = 0;
    sleeptime.tv_nsec = 50000000; // 50 ms.
    while (server->is_running){
	pthread_rwlock_wrlock(&server->state_lock);
	pthread_rwlock_wrlock(&server->players_lock);
	Server_tick(server);
	pthread_rwlock_unlock(&server->state_lock);
	pthread_rwlock_unlock(&server->players_lock);
	nanosleep(&sleeptime, NULL);
    }
    pthread_join(server->distributor_thread, NULL);
    logmsg(LOG_INFO, "Server shutting down!");

    return 0;
}
Пример #10
0
/** thread function **/
void * executeThreads(void *rank)
{
    srand(time(NULL));      // initialize random seed
    while(totalOps > 0)
    {
        /** mutex for totalOps global variable**/
        pthread_mutex_lock(&mutexTotalOps);
        totalOps--;
        pthread_mutex_unlock(&mutexTotalOps);

        if (insertFunctionCount == 0 && memberFunctionCount == 0 && deleteFunctionCount == 0)
        {
            break;
        }

        int rndVal=rand()%3+1;   // generate random value from 1 to 1000

        /** adjust pre defined ranges by considering function count **/
        if(memberFunctionCount == 0)
        {

            if (insertFunctionCount == 0)
            {
                rndVal=3;
            }
            else if(deleteFunctionCount == 0)
            {
                rndVal=2;
            }
            else
            {
                rndVal=rand()%2+2;
            }

        }
        else if (insertFunctionCount == 0)
        {
            if (memberFunctionCount == 0)
            {
                rndVal=3;
            }
            else if(deleteFunctionCount == 0)
            {
                rndVal=1;
            }
            else
            {
                int array[]= {1,3};
                rndVal=array[rand()%2];
            }

        }
        else if(deleteFunctionCount == 0)
        {
            if (memberFunctionCount == 0)
            {
                rndVal=2;
            }
            else if(insertFunctionCount == 0)
            {
                rndVal=1;
            }
            else
            {
                rndVal=rand()%2+1;
            }
        }

        /** execute relevant operation according to the pre defined limit ranges **/
        if(rndVal == 1)
        {
            pthread_rwlock_rdlock(&rwlock);
            //pthread_mutex_lock(&mutexList);
            member(rand()%1500+1,(int)rank);
            //pthread_mutex_unlock(&mutexList);
            pthread_rwlock_unlock(&rwlock);
        }
        else if(rndVal == 2)
        {
            //pthread_mutex_lock(&mutexList);
            pthread_rwlock_wrlock(&rwlock);
            insert_node(rand()%1000+1001,(int)rank);
            //pthread_mutex_unlock(&mutexList);
            pthread_rwlock_unlock(&rwlock);
        }
        else if(rndVal == 3)
        {
            pthread_rwlock_wrlock(&rwlock);
            //pthread_mutex_lock(&mutexList);
            delete_node(rand()%1500+1,(int)rank);
            //pthread_mutex_unlock(&mutexList);
            pthread_rwlock_unlock(&rwlock);
        }
    }
    return NULL;
}
Пример #11
0
 void lock ()
 {
     int status = pthread_rwlock_wrlock(&m_rwlock);
     POMAGMA_ASSERT1(status == 0, "pthread_rwlock_wrlock failed");
 }
Пример #12
0
// wlock the core 
int RG_core_wlock( struct RG_core* rg ) {
   
   return pthread_rwlock_wrlock( &rg->lock );
}
Пример #13
0
/** Configure dessert logging framework and sets up logging.
 *
 * @param opts OR'd flags - @see DESSERT_LOG_*
 * @return DESSERT_OK
 *
 * %DESCRIPTION:
 **/
dessert_result dessert_logcfg(uint16_t opts) {
    char dessert_logprefix[32];
    snprintf(dessert_logprefix, sizeof(dessert_logprefix), "dessert/%s", dessert_proto);

    pthread_rwlock_wrlock(&dessert_cfglock);

    /* configure logging */
    if((opts & DESSERT_LOG_SYSLOG) && !(opts & DESSERT_LOG_NOSYSLOG)) {
        if(!(_dessert_logflags & _DESSERT_LOGFLAG_SYSLOG)) {
            /* initialize syslog channel */
            openlog(dessert_logprefix, LOG_PID, LOG_DAEMON);
        }

        _dessert_logflags |= _DESSERT_LOGFLAG_SYSLOG;
    }
    else if(!(opts & DESSERT_LOG_SYSLOG) && (opts & DESSERT_LOG_NOSYSLOG)) {
        if(_dessert_logflags & _DESSERT_LOGFLAG_SYSLOG) {
            /* close syslog channel */
            closelog();
        }

        _dessert_logflags &= ~_DESSERT_LOGFLAG_SYSLOG;
    }

    if((opts & DESSERT_LOG_STDERR) && !(opts & DESSERT_LOG_NOSTDERR)
       && !(_dessert_status & _DESSERT_STATUS_DAEMON)) {
        _dessert_logflags |= _DESSERT_LOGFLAG_STDERR;
    }
    else if((!(opts & DESSERT_LOG_STDERR) && (opts & DESSERT_LOG_NOSTDERR))
            || (_dessert_status & _DESSERT_STATUS_DAEMON)) {
        _dessert_logflags &= ~_DESSERT_LOGFLAG_STDERR;
    }

#ifdef HAVE_LIBZ

    // enable or disable compression
    if((opts & DESSERT_LOG_GZ) && !(opts & DESSERT_LOG_NOGZ)) {
        _dessert_logflags |= _DESSERT_LOGFLAG_GZ;
    }
    else if((!(opts & DESSERT_LOG_GZ) && (opts & DESSERT_LOG_NOGZ))) {
        _dessert_logflags &= ~_DESSERT_LOGFLAG_GZ;
    }

#endif

    if((opts & DESSERT_LOG_FILE) && !(opts & DESSERT_LOG_NOFILE)
       && (_dessert_logfd != NULL
#ifdef HAVE_LIBZ
           || _dessert_logfdgz != NULL
#endif
          )) {
        _dessert_logflags |= _DESSERT_LOGFLAG_LOGFILE;
    }
    else if((!(opts & DESSERT_LOG_FILE) && (opts & DESSERT_LOG_NOFILE))
            || (_dessert_logfd == NULL
#ifdef HAVE_LIBZ
                && _dessert_logfdgz == NULL
#endif
               )) {
        _dessert_logflags &= ~_DESSERT_LOGFLAG_LOGFILE;
    }

    if((opts & DESSERT_LOG_RBUF) && !(opts & DESSERT_LOG_NORBUF)) {
        _dessert_logflags |= _DESSERT_LOGFLAG_RBUF;
    }
    else if(!(opts & DESSERT_LOG_RBUF) && (opts & DESSERT_LOG_NORBUF)) {
        _dessert_logflags &= ~_DESSERT_LOGFLAG_RBUF;
    }

    pthread_rwlock_unlock(&dessert_cfglock);

    return DESSERT_OK;
}
Пример #14
0
/** command "logging ringbuffer" */
int _dessert_cli_logging_ringbuffer(struct cli_def* cli, char* command, char* argv[], int argc) {
    int newlen = -1;

    if(argc != 1 || (newlen = (int) strtol(argv[0], NULL, 10)) < 0) {
        cli_print(cli, "usage %s [buffer length]\n", command);
        return CLI_ERROR;
    }

    if(newlen == _dessert_logrbuf_len) {
        return CLI_OK;
    }

    if(newlen == 0) {
        cli_print(cli,
                  "will not set buffer length to 0 - use no logging ringbuffer instead\n");
        return CLI_ERROR;
    }

    pthread_rwlock_wrlock(&_dessert_logrbuf_len_lock);

    /* make logging buffer larger - easy if not ENOMEM*/
    if(newlen > _dessert_logrbuf_len) {
        _dessert_logrbuf = realloc(_dessert_logrbuf, newlen
                                   * DESSERT_LOGLINE_MAX * sizeof(char));

        if(_dessert_logrbuf == NULL) {
            _dessert_logrbuf_len = 0;
            _dessert_logrbuf_cur = 0;
        }
        else {
            _dessert_logrbuf_len = newlen;
        }

        dessert_logcfg(DESSERT_LOG_RBUF);
        /* make logging buffer smaller - pain in the ass */
    }
    else if(newlen < _dessert_logrbuf_len) {
        /* move current log buffer if needed */
        if(_dessert_logrbuf_cur > newlen) {
            memmove(_dessert_logrbuf, _dessert_logrbuf + (DESSERT_LOGLINE_MAX
                    *(_dessert_logrbuf_cur - newlen)), newlen
                    * DESSERT_LOGLINE_MAX * sizeof(char));
            _dessert_logrbuf_cur -= newlen;
        }

        _dessert_logrbuf = realloc(_dessert_logrbuf, newlen
                                   * DESSERT_LOGLINE_MAX * sizeof(char));

        if(_dessert_logrbuf == NULL) {
            _dessert_logrbuf_len = 0;
            _dessert_logrbuf_cur = 0;
        }
        else {
            _dessert_logrbuf_len = newlen;
        }
    }
    else {
        dessert_err("this never happens");
    }

    if(_dessert_logrbuf_used > _dessert_logrbuf_len - 1) {
        _dessert_logrbuf_used = _dessert_logrbuf_len - 1;
    }

    pthread_rwlock_unlock(&_dessert_logrbuf_len_lock);
    return CLI_OK;
}
Пример #15
0
void
sharddir_wrlock(struct sharddir *shardd)
{
	CHECK_OBJ_NOTNULL(shardd, SHARDDIR_MAGIC);
	AZ(pthread_rwlock_wrlock(&shardd->mtx));
}
Пример #16
0
void RWLock_WriteLock(RWLock *rwlock) { 
	pthread_rwlock_wrlock(&rwlock->rw_); 
}
Пример #17
0
	int lock_w()
	{
		return pthread_rwlock_wrlock(&locker);
	}
Пример #18
0
 void acquireWrite() const {
   PROFILE_MUTEX_START_LOCK();
   pthread_rwlock_wrlock(&rw_lock_);
   PROFILE_MUTEX_LOCKED();
 }
Пример #19
0
Файл: 4-1.c Проект: 8l/rose
int main()
{
	int cnt;
	handler_called = 0;

	if(pthread_rwlock_init(&rwlock, NULL) != 0)
	{
		printf("main: Error at pthread_rwlock_init()\n");
		return PTS_UNRESOLVED;
	}
	
	printf("main: attempt write lock\n");
	if(pthread_rwlock_wrlock(&rwlock) != 0)
	{
		printf("main: Error at pthread_rwlock_wrlock()\n");
		return PTS_UNRESOLVED;
	} else
		printf("main: acquired write lock\n");

	thread_state = NOT_CREATED_THREAD;
	if(pthread_create(&sig_thread, NULL, th_fn, NULL) != 0)
	{
		printf("main: Error at pthread_create()\n");
		return PTS_UNRESOLVED;
	}
	
	/* wait at most 3 seconds for sig_thread to block*/
	cnt = 0;
	do{
		sleep(1);
	}while(thread_state != EXITING_THREAD && cnt++ < 3);
	
	if(thread_state == EXITING_THREAD)
	{
		printf("Test FAILED: thread did not block on read lock when a writer holds the lock\n");
		exit(PTS_FAIL);		
	}
	else if(thread_state != ENTERED_THREAD) 
	{
		printf("Unexpected thread state: %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}

	/* sig_thread is blocking */
	printf("main: fire SIGUSR1 to sig_thread\n");
	if(pthread_kill(sig_thread, SIGUSR1) != 0)
	{
		printf("main: failed to send SIGUSER to sig_thread\n");
		exit(PTS_UNRESOLVED);
	}

	/* wait at most 3 seconds for the signal to be handled */		
	cnt = 0;
	do{
		sleep(1);
	}while(handler_called == 0 && cnt++ < 3);
	
	if(handler_called != 1)
	{
		printf("SIGUSR1 was not caught by sig_thread\n");
		exit(PTS_UNRESOLVED);
	}

	/* sig_thread resume to block? */
	cnt = 0;
	do{
		sleep(1);
	}while(thread_state != EXITING_THREAD && cnt++ < 3);	

	if(thread_state == EXITING_THREAD)
	{
		printf("Test FAILED: upon return from signal handler, sig_thread does not resume to block\n");
		exit(PTS_FAIL);
	}else if(thread_state != ENTERED_THREAD)
	{
		printf("Unexpected thread state: %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}
	
	printf("sig_thread: correctly still blocking after signal handler returns\n");	
	printf("main: unlock write lock\n");
	if(pthread_rwlock_unlock(&rwlock) != 0)
	{
		printf("main: Failed to release write lock\n");
		exit(PTS_UNRESOLVED);
	}
	
	/* sig_thread got the read lock? */
	cnt = 0;
	do{
		sleep(1);
	}while(thread_state != EXITING_THREAD && cnt++ < 3);
	
	if(thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: sig_thread blocked on read lock when writer release the lock\n");
		exit(PTS_FAIL);	
	}else if(thread_state != EXITING_THREAD)
	{
		printf("Unexpected thread state: %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}
	
	if(pthread_join(sig_thread, NULL) != 0)
	{
		printf("main: failed at pthread_join()\n");	
		exit(PTS_UNRESOLVED);
	}
	
	if(pthread_rwlock_destroy(&rwlock) != 0)
	{
		printf("main: failed at pthread_rwlock_destroy()\n");
		exit(PTS_UNRESOLVED);
	}
	
	printf("Test PASSED\n");
	return PTS_PASS;	
}
Пример #20
0
int main()
{
	int cnt = 0;
	pthread_t thread0, thread1, thread2;
	
	if(pthread_rwlock_init(&rwlock, NULL) != 0)
	{
		printf("Error at pthread_rwlock_init()\n");
		return PTS_UNRESOLVED;
	}

	printf("main: create thread0\n");
	thread_state = NOT_CREATED_THREAD;
	if(pthread_create(&thread0, NULL, fn_wr, NULL) != 0)
	{
		printf("Error creating thread0\n");
		return PTS_UNRESOLVED;
	}
	
	/* thread0 should not block at all since no one else has locked rwlock */

	cnt = 0;
	expired = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 2*TIMEOUT); 
	
	if(thread_state == EXITING_THREAD)
	{
		if(expired == 1)
		{
			printf("Test FAILED: the timer expired\n");
			exit(PTS_FAIL);
		}
		else
			printf("thread0 correctly acquired the write lock.\n");
	}
	else if(thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: thread0 incorrectly blocked on timedwrlock\n");
		exit(PTS_FAIL);
	}
	else
	{
		printf("Unexpected state for thread0 %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}	
	
	if(pthread_join(thread0, NULL) != 0)
	{
		printf("Error when joining thread0\n");
		return PTS_UNRESOLVED;
	}
	
	printf("main: attempt read lock\n");
	/* We have no lock, this read lock should succeed */	
	if(pthread_rwlock_rdlock(&rwlock) != 0)
	{
		printf("Error at pthread_rwlock_rdlock()\n");
		return PTS_UNRESOLVED;
	}
	printf("main: acquired read lock\n");
	
	thread_state = NOT_CREATED_THREAD;
	
	printf("main: create thread1\n");
	if(pthread_create(&thread1, NULL, fn_wr, NULL) != 0)
	{
		printf("Error when creating thread1\n");
		return PTS_UNRESOLVED;
	}
	
	/* If the shared data is not altered by child after TIMEOUT*2 seconds,
	   we regard it as blocked */

	/* we expect the thread to expire blocking after timeout*/
	cnt = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 2*TIMEOUT); 
		
	if(thread_state == EXITING_THREAD)
	{
		/* the child thread does not block, check the time interval */
		struct timeval time_diff;
		time_diff.tv_sec = currsec2.tv_sec - currsec1.tv_sec;
		time_diff.tv_usec = currsec2.tv_usec - currsec1.tv_usec;
		if (time_diff.tv_usec < 0)
		{
			--time_diff.tv_sec;
			time_diff.tv_usec += 1000000;
		}
		if(time_diff.tv_sec < TIMEOUT)
		{
			printf("Test FAILED: the timer expired and blocking "
				"was terminated, but the timeout is not correct: "
				"expected to wait for %d, but waited for %ld.%06ld\n", 
				TIMEOUT, (long)time_diff.tv_sec, 
				(long)time_diff.tv_usec);
			exit(PTS_FAIL);
		}
		else
			printf("thread1 correctly expired at timeout.\n");
	}
	else if(thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: wait is not terminated even "
			"when the timer expired\n");
		exit(PTS_FAIL);
	}
	else
	{
		printf("Unexpected state for thread1 %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}
	
	printf("main: unlock read lock\n");
	if(pthread_rwlock_unlock(&rwlock) != 0)
	{
		printf("Error when release read lock\n");
		exit(PTS_UNRESOLVED);
	}
	
	if(pthread_join(thread1, NULL) != 0)
	{
		printf("Error when joining thread1\n");
		return PTS_UNRESOLVED;
	}
	
	printf("main: attempt write lock\n");
	if(pthread_rwlock_wrlock(&rwlock) != 0)
	{
		printf("Error at pthread_rwlock_wrlock()\n");
		return PTS_UNRESOLVED;	
	}
	printf("main: acquired write lock\n");

	thread_state = NOT_CREATED_THREAD;
	cnt = 0;
	printf("main: create thread2\n");
	if(pthread_create(&thread2, NULL, fn_wr, NULL) != 0)
	{
		printf("Error when creating thread2\n");
		return PTS_UNRESOLVED;
	}
	
	/* we expect thread2 to expire blocking after timeout */
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 2*TIMEOUT); 
	
	if(thread_state == EXITING_THREAD)
	{
		/* the child thread does not block, check the time interval */
		struct timeval time_diff;
		time_diff.tv_sec = currsec2.tv_sec - currsec1.tv_sec;
		time_diff.tv_usec = currsec2.tv_usec - currsec1.tv_usec;
		if (time_diff.tv_usec < 0)
		{
			--time_diff.tv_sec;
			time_diff.tv_usec += 1000000;
		}
		if(time_diff.tv_sec < TIMEOUT)
		{
			printf("Test FAILED: for thread 2, the timer expired "
			"and waiter terminated, but the timeout is not correct\n");
			exit(PTS_FAIL);
		}
		else
			printf("thread2 correctly expired at timeout.\n");
		
	}
	else if(thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: for thread2, wait is not terminated "
			"even when the timer expired\n");
		exit(PTS_FAIL);
	}
	else
	{
		printf("Unexpected state for thread2 %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}

	printf("main: unlock write lock\n");
	thread_state = NOT_CREATED_THREAD;
	if(pthread_rwlock_unlock(&rwlock) != 0)
	{
		printf("Error releasing write lock\n");
		exit(PTS_UNRESOLVED);
	}

	if(pthread_rwlock_destroy(&rwlock) != 0)
	{
		printf("Error at pthread_rwlockattr_destroy()\n");
		return PTS_UNRESOLVED;
	}	

	printf("Test PASSED\n");
	return PTS_PASS;
}
Пример #21
0
static inline void dictionary_write_lock(DICTIONARY *dict) {
	if(likely(dict->rwlock)) {
		// debug(D_DICTIONARY, "Dictionary WRITE lock");
		pthread_rwlock_wrlock(dict->rwlock);
	}
}
Пример #22
0
Файл: init.c Проект: Fyleo/rtems
void *POSIX_Init(
  void *argument
)
{
  int                 i;
  int                 status;
  pthread_t           threadId;
  pthread_attr_t      attr;
  struct sched_param  param;
  pthread_rwlockattr_t rw_attr;

  TEST_BEGIN();

  /*
   * Deliberately create the lock BEFORE the threads.  This way the
   * threads should preempt this thread and block as they are created.
   */
  status = pthread_rwlockattr_init( &rw_attr );
  rtems_test_assert( status == 0 );
  status = pthread_rwlock_init( &rwlock, &rw_attr );
  rtems_test_assert( status == 0 );

  /*
   * Obtain the lock so the threads will block.
   */
  status = pthread_rwlock_wrlock(&rwlock);
  rtems_test_assert( status == 0 );

  /*
   * Now lower our priority
   */
  status = pthread_attr_init( &attr );
  rtems_test_assert( status == 0 );

  status = pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
  rtems_test_assert( status == 0 );

  status = pthread_attr_setschedpolicy( &attr, SCHED_RR );
  rtems_test_assert( status == 0 );

  param.sched_priority = 2;
  status = pthread_attr_setschedparam( &attr, &param );
  rtems_test_assert( status == 0 );

  /*
   * And create rest of threads as more important than we are.  They
   * will preempt us as they are created and block.
   */
  for ( i=0 ; i < OPERATION_COUNT ; i++ ) {

    param.sched_priority = 3 + i;
    status = pthread_attr_setschedparam( &attr, &param );
    rtems_test_assert( status == 0 );

    status = pthread_create(
      &threadId,
      &attr,
      (i == OPERATION_COUNT - 1) ? Low : Middle,
      NULL
    );
    rtems_test_assert( status == 0 );
  }

  /*
   * Now start the timer which will be stopped in Low
   * Release the lock.  Threads unblock and preempt.
   */
  benchmark_timer_initialize();

    status = pthread_rwlock_unlock(&rwlock);
      /* thread switch occurs */

  /* should never return */
  rtems_test_assert( FALSE );
  return NULL;
}
Пример #23
0
void batman_db_wlock() {
    pthread_rwlock_wrlock(&rwlock);
}
Пример #24
0
static void reap_hash_table(hash_table_t * ht_reap)
{
  struct rbt_head     * head_rbt;
  hash_data_t         * pdata = NULL;
  uint32_t              i;
  int                   v4, rc;
  struct rbt_node     * pn;
  nfs_client_id_t     * pclientid;
  nfs_client_record_t * precord;

  /* For each bucket of the requested hashtable */
  for(i = 0; i < ht_reap->parameter.index_size; i++)
    {
      head_rbt = &ht_reap->partitions[i].rbt;

 restart:
      /* acquire mutex */
      pthread_rwlock_wrlock(&ht_reap->partitions[i].lock);

      /* go through all entries in the red-black-tree*/
      RBT_LOOP(head_rbt, pn)
        {
          pdata = RBT_OPAQ(pn);

          pclientid = (nfs_client_id_t *)pdata->buffval.pdata;
          /*
           * little hack: only want to reap v4 clients
           * 4.1 initializess this field to '1'
           */
          v4 = (pclientid->cid_create_session_sequence == 0);

          P(pclientid->cid_mutex);

          if(!valid_lease(pclientid) && v4)
            {
              inc_client_id_ref(pclientid);

              /* Take a reference to the client record */
              precord = pclientid->cid_client_record;
              inc_client_record_ref(precord);

              V(pclientid->cid_mutex);

              pthread_rwlock_unlock(&ht_reap->partitions[i].lock);

              if(isDebug(COMPONENT_CLIENTID))
                {
                  char str[HASHTABLE_DISPLAY_STRLEN];

                  display_client_id_rec(pclientid, str);

                  LogFullDebug(COMPONENT_CLIENTID,
                               "Expire index %d %s",
                               i, str);
                }

              /* Take cr_mutex and expire clientid */
              P(precord->cr_mutex);

              rc = nfs_client_id_expire(pclientid);

              V(precord->cr_mutex);

              dec_client_id_ref(pclientid);
              dec_client_record_ref(precord);
              if(rc)
                goto restart;
            }
          else
            {
              V(pclientid->cid_mutex);
            }

          RBT_INCREMENT(pn);
        }

      pthread_rwlock_unlock(&ht_reap->partitions[i].lock);
    }
Пример #25
0
// write-lock a manifest 
static int SG_manifest_wlock( struct SG_manifest* manifest ) {
   return pthread_rwlock_wrlock( &manifest->lock );
}
Пример #26
0
MITLogRetValue MITLogWrite(MITLogLevel level, const char *fmt, ...)
{
    // 1. generate the string
    int n, size = 100;      // suppose the message need no more than 100 bytes
    char *tarp = NULL, *np = NULL;
    va_list ap;
    if ((tarp = malloc(size)) == NULL) {
        return MITLOG_RETV_ALLOC_MEM_FAIL;
    }
    while (1) {
        // try to print the allocated space
        va_start(ap, fmt);
        n = vsnprintf(tarp, size, fmt, ap);
        va_end(ap);
        if (n > -1 && n < size) {
            break;
        }
        // try more space
        if (n > -1) {      // glibc 2.1
            size = n + 1;  // 1 is for the '\0'
        } else {           // glibc 2.0
            size = n * 2;  // twice the old size
        }
        if ((np = realloc(tarp, size)) == NULL) {
            free(tarp);
            return MITLOG_RETV_ALLOC_MEM_FAIL;
        } else {
            tarp = np;
        }
    }
    // 2. add prefix and suffix to the message
    time_t now = time(NULL);
    char timeStr[48] = {0};
    snprintf(timeStr, 48, "[%ld]", now);
    long long sumLen = strlen(timeStr) + 1 + strlen(tarp) \
			+ strlen("\n") + 5;   // 5 keep enough space and last space is '\0'
    char *tarMessage = (char *)calloc(sumLen, sizeof(char));
    if (!tarMessage) {
        free(tarp);
        tarp = NULL;
        return MITLOG_RETV_ALLOC_MEM_FAIL;
    }
    sprintf(tarMessage, "%s %s\n", timeStr, tarp);
    sumLen = strlen(tarMessage);
    
    free(tarp);
    np = tarp = NULL;
    //MIT_dprintf("target message:%s", tarMessage);
    MITLogFileIndex aryIndex = MITGetIndexForLevel(level);
    
#if MITLOG_DEBUG_ENABLE
    fprintf(originFilePointers[aryIndex], "%-10s %s", MITLogLevelHeads[aryIndex], tarMessage);
#else
    // 3. add target message into buffer or file
    pthread_rwlock_wrlock(&bufferRWlock);
    long long bufferUesedSize = strlen(logFileBuffer[aryIndex]);
    if (MITLogBufferMaxSize[aryIndex] - bufferUesedSize > sumLen) {
        // write into buffer
        strcat(logFileBuffer[aryIndex], tarMessage);
        pthread_rwlock_unlock(&bufferRWlock);
    } else {
        MIT_dputs("String write into file*****************");
        pthread_rwlock_unlock(&bufferRWlock);
        
        pthread_rwlock_rdlock(&bufferRWlock);
        // 1. flush the buffer
        long long firstLen = strlen(logFileBuffer[aryIndex]);
        MITLogWriteFile(aryIndex, logFileBuffer[aryIndex], firstLen);
        pthread_rwlock_unlock(&bufferRWlock);
        
        pthread_rwlock_wrlock(&bufferRWlock);
        long long secondLen = strlen(logFileBuffer[aryIndex]);
        long long subNum = secondLen - firstLen;
        if (subNum == 0) {
            // empty the buffer
            memset(logFileBuffer[aryIndex], 0, firstLen);
        } else if(subNum > 0){
            memset(logFileBuffer[aryIndex], 0, firstLen);
            memmove(logFileBuffer[aryIndex], logFileBuffer[aryIndex]+firstLen, subNum);
            memset(logFileBuffer[aryIndex]+subNum, 0, MITLogBufferMaxSize[aryIndex]-subNum);
        }
        // 2. write into origin file or buffer
        if (sumLen < MITLogBufferMaxSize[aryIndex]) {
            // write into buffer
            strcat(logFileBuffer[aryIndex], tarMessage);
            pthread_rwlock_unlock(&bufferRWlock);
        } else {
            pthread_rwlock_unlock(&bufferRWlock);
            // write into origin file directly
            MITLogWriteFile(aryIndex, tarMessage, sumLen);
        }
    }
    
    free(tarMessage);
    tarMessage = NULL;
#endif
    return MITLOG_RETV_SUCCESS;
}
Пример #27
0
void uv_rwlock_wrlock(uv_rwlock_t* rwlock) {
  if (pthread_rwlock_wrlock(rwlock))
    abort();
}
Пример #28
0
int
couchdb_update(uint64_t key, char *data, size_t len)
{
	char *db_key = NULL;
	lcb_size_t	key_size;
	lcb_error_t	ret;
	int	lock_result = -1;
	lcb_store_cmd_t item;
	const lcb_store_cmd_t *const store_items[] = { &item };
	char *compressed_data = NULL;
	size_t	compressed_len = 0;
	int	res = 0;

	compressed_len = snappy_max_compressed_length(len);
	compressed_data = (char *)malloc(compressed_len);
	if (compressed_data == NULL) {
		syslog(LOG_ERR, "%s: Unable to allocate memory for compressed_data\n", __FUNCTION__);
		return (-ENOMEM);
	}

	if ((res = snappy_compress((const char *)data, len,
 			compressed_data, &compressed_len)) != SNAPPY_OK) {
		free(compressed_data);
		return (-res);
	}

	memset(&item, 0, sizeof(lcb_store_cmd_t));
	db_key = (char *) malloc(MAX_KEY_SIZE);
	if (NULL == db_key) {
		syslog(LOG_ERR, "%s: Unable to allocate memory for db_key\n",
			__FUNCTION__);
		return -ENOMEM;
	}
	sprintf(db_key,"%"PRId64"", key);
	USYSLOG(LOG_INFO, "%s: set1 %"PRId64" %s %s, \n", __FUNCTION__, key,
		(char *) data, db_key);
	key_size = strlen(db_key);

	item.v.v0.key = db_key;
	item.v.v0.nkey = key_size;
	item.v.v0.bytes = compressed_data;
	item.v.v0.nbytes = compressed_len;
	item.v.v0.operation = LCB_REPLACE;

	lock_result = pthread_rwlock_wrlock(&db_rwlock);
	if (lock_result != 0) {
		syslog(LOG_ERR, "%s: Failed to obtain write lock. Error = %d\n",
			__FUNCTION__, errno);
		return -errno;
	}

	ret = lcb_store(couchdb_handle, NULL, 1, store_items);
	if (ret != LCB_SUCCESS) {
		syslog(LOG_ERR, "%s: lcb_store failed with error %s\n",
			__FUNCTION__, lcb_strerror(couchdb_handle, ret));
		return -ret;
	}
	/* Block the thread till this operation completes */
	lcb_wait(couchdb_handle);

	pthread_rwlock_unlock(&db_rwlock);

	return  (1);

}
Пример #29
0
static void
apteryx__set (Apteryx__Server_Service *service,
              const Apteryx__Set *set,
              Apteryx__OKResult_Closure closure, void *closure_data)
{
    Apteryx__OKResult result = APTERYX__OKRESULT__INIT;
    const char *path = NULL;
    const char *value = NULL;
    result.result = 0;
    int validation_result = 0;
    int validation_lock = 0;
    int proxy_result = 0;
    bool db_result = false;
    int i;

    /* Check parameters */
    if (set == NULL || set->n_sets == 0 || set->sets == NULL)
    {
        ERROR ("SET: Invalid parameters.\n");
        result.result = -EINVAL;
        closure (&result, closure_data);
        INC_COUNTER (counters.set_invalid);
        return;
    }
    INC_COUNTER (counters.set);

    /* Debug */
    for (i=0; apteryx_debug && i<set->n_sets; i++)
    {
        DEBUG ("SET: %s = %s\n", set->sets[i]->path, set->sets[i]->value);
    }

    /* Proxy first */
    for (i=0; i<set->n_sets; i++)
    {
        path = set->sets[i]->path;
        value = set->sets[i]->value;
        if (value && value[0] == '\0')
            value = NULL;

        proxy_result = proxy_set (path, value, set->ts);
        if (proxy_result == 0)
        {
            /*  Result success */
            DEBUG ("SET: %s = %s proxied\n", path, value);
            /* Mark the set as processed */
            notify_watchers (set->sets[i]->path);
            free (set->sets[i]->path);
            set->sets[i]->path = NULL;
        }
        else if (proxy_result < 0)
        {
            result.result = proxy_result;
            goto exit;
        }
    }

    /* Validate */
    for (i=0; i<set->n_sets; i++)
    {
        path = set->sets[i]->path;
        if (!path)
            continue;
        value = set->sets[i]->value;
        if (value && value[0] == '\0')
            value = NULL;

        /* Validate new data */
        validation_result = validate_set (path, value);
        if (validation_result != 0)
            validation_lock++;
        if (validation_result < 0)
        {
            DEBUG ("SET: %s = %s refused by validate\n", path, value);
            result.result = validation_result;
            goto exit;
        }
    }

    /* Set in the database */
    pthread_rwlock_wrlock (&db_lock);
    for (i=0; i<set->n_sets; i++)
    {
        path = set->sets[i]->path;
        if (!path)
            continue;
        value = set->sets[i]->value;
        if (value && value[0] == '\0')
            value = NULL;

        /* Add/Delete to/from database */
        if (value)
            db_result = db_add_no_lock (path, (unsigned char*)value, strlen (value) + 1, set->ts);
        else
            db_result = db_delete_no_lock (path, set->ts);
        if (!db_result)
        {
            DEBUG ("SET: %s = %s refused by DB\n", path, value);
            result.result = -EBUSY;
            pthread_rwlock_unlock (&db_lock);
            goto exit;
        }
    }
    pthread_rwlock_unlock (&db_lock);

    /* Set succeeded */
    result.result = 0;

exit:
    /* Return result and notify watchers */
    if (validation_result >= 0 && result.result == 0)
    {
        /* Notify watchers */
        for (i=0; i<set->n_sets; i++)
        {
            if (set->sets[i]->path)
                notify_watchers (set->sets[i]->path);
        }
    }

    /* Return result */
    closure (&result, closure_data);

    /* Release validation lock - this is a sensitive value */
    while (validation_lock)
    {
        DEBUG("SET: unlocking mutex\n");
        pthread_mutex_unlock (&validating);
        validation_lock--;
    }
    return;
}
Пример #30
0
void CUserQueryUpdate::Core()
{
	std::string strToken,strTokenValue,strReceiveBuffer;
	Json::Value jValue,jRoot,jResult;
	Json::Reader jReader;
	Json::FastWriter jFastWriter;
	std::string sts="yd_zhejiang_mobile_token";
	std::string strMysqlRecord;
	const char *pchSqlPermissions = "select name,password,query_count,goods_count,goods_perm,permissions from dmp_user_permissions";
	BDXPERMISSSION_S mUserInfoVecFields;
	std::string strUserName;
	int times = 0;
	int currentPool;
	std::map<std::string,BDXPERMISSSION_S> temp_mapUserInfo;

	std::string httpDianxinGet="/bdapi/restful/fog/asia/getSingleUserTags/ctyun_bdcsc_asia/1ebb3c5d8a574e74b2e6156a5c010cba.json?key=uid_m310001_3_1_20160315&tablename=vendoryx_2";
	char m_httpReq[_8KBLEN],remoteBuffer[_8KBLEN];
	memset(m_httpReq, 0, _8KBLEN);
		
	while(true)
	{
		times=7;	
		int first_row = 1;
		#if 0
        if(m_pTokenRedis->UserGet(sts,strToken))
        {
	        //if(jReader.parse(strToken, jValue))
	        //{
	        //      strTokenValue = jValue[TOKEN].asString();
	            if(strToken.compare(g_strTokenString)!=0)
	            {
	                    pthread_rwlock_wrlock(&p_rwlock);
	                    g_strTokenString = strToken;
	                    g_iNeedUpdateToken = 1;
	                    pthread_rwlock_unlock(&p_rwlock);
	            }
	        //}
        }
        //st_emrtb_ip_port_weight_flag = 0;
	  	printf("g_strTokenString = %s\n",g_strTokenString.c_str());
		#endif

	 	#define __MONITOR_API__
	  	#ifdef __MONITOR_API__

		//MonitorRemoteApiWangGuan();
		//MonitorRemoteApiHuaWei();
									
		#endif //__MONITOR_API__

	#ifdef __CONECT_POOL__
			pthread_mutex_lock (&connectPoolMutex);
			printf("Line:%d,,BEGIN CHECK InitConnectPool=%d,totalConnectPool=%d,m_uiTotalThreadsNum=%d\n",__LINE__,InitConnectPool,totalConnectPool,m_uiTotalThreadsNum);
			if ( InitConnectPool == 0 || (totalConnectPool < m_uiTotalThreadsNum))
			{
				currentPool = m_uiTotalThreadsNum - totalConnectPool;
				printf("Line:%d,initing  pool.....\n",__LINE__);
				for(int i = 0 ;i< currentPool;i++)
				{
					//CTcpSocket *socket;
					taskConnectPool.socket = new CTcpSocket(8080,std::string("111.235.158.136"));
					//taskConnectPool.socket = new CTcpSocket(58001,std::string("0.0.0.0"));
					if(taskConnectPool.socket->TcpConnect()==0)
					{	
						printf("Line:%d,connecting....\n",__LINE__);
						taskConnectPool.m_bStatus = true;

						sprintf(m_httpReq,"GET %s HTTP/1.1\r\nHost: %s\r\nAccept-Encoding: identity\r\n\r\n",httpDianxinGet.c_str(),std::string("111.235.158.136:8080").c_str());
						taskConnectPool.socket->TcpSetKeepAliveOn();
						if(taskConnectPool.socket->TcpWrite(m_httpReq,strlen(m_httpReq))!=0)
						{
							taskConnectPool.isConnect = 1;
							m_vevtorConnectPool.push_back(taskConnectPool);
							totalConnectPool++;
							memset(remoteBuffer,0,_8KBLEN);
							taskConnectPool.socket->TcpRead(remoteBuffer,_8KBLEN);
							strReceiveBuffer = std::string(remoteBuffer);
							printf("Line:%d,strReceiveBuffer=%s\n",__LINE__,strReceiveBuffer.c_str());

						}
						else
						{
							taskConnectPool.isConnect = 0;
							taskConnectPool.socket->TcpClose();
						}
					}
					else
					{	
						taskConnectPool.isConnect = 0;
						taskConnectPool.socket->TcpClose();
					}
				}		
				InitConnectPool = 1;
			}

			printf("Line:%d,,AFTER CHECK InitConnectPool=%d,totalConnectPool=%d,m_uiTotalThreadsNum=%d\n",__LINE__,InitConnectPool,totalConnectPool,m_uiTotalThreadsNum);
		 	printf("Line:%d,m_vevtorConnectPool.size =%d\n",__LINE__,m_vevtorConnectPool.size());
			std::vector<TASKCONNECT_S>::iterator itr;
			for(itr = m_vevtorConnectPool.begin();itr!=m_vevtorConnectPool.end();itr++)
			{
				if( itr->m_bStatus	==	true )
				{	
					 if(itr->isConnect == 1)
					 {
						 itr->m_bStatus  =	 false;
						 sprintf(m_httpReq,"GET %s HTTP/1.1\r\nHost: %s\r\nAccept-Encoding: identity\r\n\r\n",httpDianxinGet.c_str(),std::string("111.235.158.136:8080").c_str());
						 itr->socket->TcpSetKeepAliveOn();
						 if(itr->socket->TcpWrite(m_httpReq,strlen(m_httpReq))!=0)
						 {
							 memset(remoteBuffer,0,_8KBLEN);
							 itr->socket->TcpRead(remoteBuffer,_8KBLEN);
							 strReceiveBuffer = std::string(remoteBuffer);
						 }
						 else
						 {
						 	printf("Line:%d,checking  pool.....error\n",__LINE__);
							printf("Line:%d,totalConnectPool  =%d\n",__LINE__,totalConnectPool);
							printf("Line:%d,m_vevtorConnectPool.size=%d\n",__LINE__,m_vevtorConnectPool.size());
							itr->isConnect = 0;
							itr->socket->TcpClose();
							m_vevtorConnectPool.erase(itr);
							totalConnectPool--;
						 }
					 }
					
				}
				itr->m_bStatus	=	true;
			}

			pthread_mutex_unlock(&connectPoolMutex);
	#endif

		printf("Line:%d,totalConnectPool=%d\n",__LINE__,totalConnectPool);
		while(times--)
		{
				temp_mapUserInfo.clear();
				if(m_stMysqlServerInfo->GetMysqlInitState())
				{
					if(m_stMysqlServerInfo->ExecuteMySql(pchSqlPermissions))
					{

						if(m_stMysqlServerInfo->MysqlUseResult())
						{	
							//m_stMysqlServerInfo->DisplayHeader();
							while(m_stMysqlServerInfo->MysqlFetchRow())
							{			
								//if(!first_row)
								{	
									strMysqlRecord = m_stMysqlServerInfo->GetColumnValue();
									//printf("strMysqlRecord = %s\n",strMysqlRecord.c_str());
									GetMysqlFieldsUserInfo(strMysqlRecord,mUserInfoVecFields,strUserName);
									temp_mapUserInfo.insert(std::pair<std::string,BDXPERMISSSION_S>(strUserName,mUserInfoVecFields));
									
								}
								first_row = 0;
							}
							m_stMysqlServerInfo->DestroyResultEnv();
							std::map<std::string,BDXPERMISSSION_S>::iterator itr;
							std::vector<std::string>::iterator itr2;
							#if 0
							printf("===================g_mapUserInfo========================\n");
							for(itr=temp_mapUserInfo.begin();itr!=temp_mapUserInfo.end();itr++)
							{	
								printf("%s ",itr->first.c_str());
								printf("%s ",itr->second.mResToken.c_str());
								printf("%d ",itr->second.mIntQueryTimes);
								printf("%d ",itr->second.mIntGoodsTimes);
								printf("%s ",itr->second.mGoodsFields.c_str());
								for(itr2=itr->second.mVecFields.begin();itr2!=itr->second.mVecFields.end();itr2++)
								{
									printf("%s ",(*itr2).c_str());
									
								}
								printf("\n");
							}
							#endif
							#if 1
							printf("===================g_mapUserInfo========================\n");
							for(itr=g_mapUserInfo.begin();itr!=g_mapUserInfo.end();itr++)
							{	
								printf("%s ",itr->first.c_str());
								printf("%s ",itr->second.mResToken.c_str());
								printf("%d ",itr->second.mIntQueryTimes);
								printf("%d ",itr->second.mIntGoodsTimes);
								printf("%s ",itr->second.mGoodsFields.c_str());
								for(itr2=itr->second.mVecFields.begin();itr2!=itr->second.mVecFields.end();itr2++)
								{
									printf("%s ",(*itr2).c_str());
								}
								printf("\n");
							}
							#endif
							if( !MapIsEqual(temp_mapUserInfo,g_mapUserInfo) )
							{
							//	g_mapUserInfo = temp_mapUserInfo;
								
								SwapMap(temp_mapUserInfo,g_mapUserInfo);
								printf("\nswap map g_mapUserInfo\n\n");				
							}

						}
						
					}

				}
				
		sleep(60);
		}	
	}

}