• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ pthread_attr_destroy函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中pthread_attr_destroy函数的典型用法代码示例。如果您正苦于以下问题:C++ pthread_attr_destroy函数的具体用法?C++ pthread_attr_destroy怎么用?C++ pthread_attr_destroy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了pthread_attr_destroy函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main

void main(int argc, char *argv[])
{
   
   int i, rc;
   pthread_attr_t attr;
   str_studente studente[N];

   pthread_mutex_init(&distributori[0], NULL);
   pthread_mutex_init(&distributori[1], NULL);
       // inizializzo i semafori
    sem_init(&coca, 0, 50);
    sem_init(&chino, 0, 10);
    sem_init(&fanta, 0, 20);
    sem_init(&sprite, 0, 20);
    
    //inizializzo thread per il gestore
    pthread_create(&gestore, NULL, gestore_routine, NULL);
    
    //inizializzo gli attributi per i thread studenti e li setto joinable
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    //inizializzo i thread studente
    for (i=0; i<N; i++) {
        studente[i].nome = i;
        studente[i].ccoca = 0;
        studente[i].csprite = 0;
        studente[i].cfanta = 0;
        studente[i].cchino = 0;
        rc = pthread_create(&studente[i].tid, &attr, studente_routine, (void *) &studente[i]);
        if (rc) {
            printf("si è verificato un errore\n");
            exit(EXIT_FAILURE);
        }
    }

    pthread_attr_destroy(&attr);
 

 sleep(30);            //dopo 30 secondi si attiva la terminazione del programma!
finito= 1;

    for(i=0; i<N; i++) {
    pthread_join(studente[i].tid, NULL);
    }

    for (i=0; i<N; i++) {
          printf("Sono lo studente %d! Ho bevuto %d coca cole, %d sprite, %d fanta, %d chinotti!\n", studente[i].nome, studente[i].ccoca, studente[i].csprite, studente[i].cfanta, studente[i].cchino);
    }



    sem_destroy(&coca);
    sem_destroy(&sprite);
    sem_destroy(&fanta);
    sem_destroy(&chino);

    pthread_mutex_destroy(&distributori[0]);
    pthread_mutex_destroy(&distributori[1]);

   pthread_exit(NULL);    


}
开发者ID:Manfrins,项目名称:CsInfoPa,代码行数:64,代码来源:mio-esame-novembre11.c


示例2: ta_process_loop

int ta_process_loop(int man_sockfd, struct com_msg_open_session *open_msg)
{
	int ret;
	pthread_t ta_logic_thread;
	pthread_attr_t attr;
	struct epoll_event cur_events[MAX_CURR_EVENTS];
	int event_count, i;
	char proc_name[MAX_PR_NAME]; /* For now */
	sigset_t sig_empty_set;

	/* Set new ta process name */
	strncpy(proc_name, open_msg->ta_so_name, MAX_PR_NAME);
	prctl(PR_SET_NAME, (unsigned long)proc_name);
	strncpy(argv0, proc_name, argv0_len);

	/* Load TA to this process */
	ret = load_ta(open_msg->ta_so_name, &interface);
	if (ret != TEE_SUCCESS || interface == NULL) {
		OT_LOG(LOG_ERR, "Failed to load the TA");
		exit(EXIT_FAILURE);
	}

	/* Note: All signal are blocked. Prepare allow set when we can accept signals */
	if (sigemptyset(&sig_empty_set)) {
		OT_LOG(LOG_ERR, "Sigempty set failed: %s", strerror(errno))
		exit(EXIT_FAILURE);
	}

	/* create an eventfd, that will allow the writer to increment the count by 1
	 * for each new event, and the reader to decrement by 1 each time, this will allow the
	 * reader to be notified for each new event, as opposed to being notified just once that
	 * there are "event(s)" pending*/
	event_fd = eventfd(0, EFD_SEMAPHORE);
	if (event_fd == -1) {
		OT_LOG(LOG_ERR, "Failed to initialize eventfd");
		exit(EXIT_FAILURE);
	}

	/* Initializations of TODO and DONE queues*/
	INIT_LIST(&tasks_todo.list);
	INIT_LIST(&tasks_done.list);

	/* Init epoll and register FD/data */
	if (init_epoll())
		exit(EXIT_FAILURE);

	/* listen to inbound connections from the manager */
	if (epoll_reg_fd(man_sockfd, EPOLLIN))
		exit(EXIT_FAILURE);

	/* listen for communications from the TA thread process */
	if (epoll_reg_fd(event_fd, EPOLLIN))
		exit(EXIT_FAILURE);

	/* Signal handling */
	if (epoll_reg_fd(self_pipe_fd, EPOLLIN))
		exit(EXIT_FAILURE);

	/* Init worker thread */
	ret = pthread_attr_init(&attr);
	if (ret) {
		OT_LOG(LOG_ERR, "Failed to create attr for thread: %s", strerror(errno))
		exit(EXIT_FAILURE);
	}

	/* TODO: Should we reserver space for thread stack? */

	ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (ret) {
		OT_LOG(LOG_ERR, "Failed set DETACHED: %s", strerror(errno))
		exit(EXIT_FAILURE);
	}

	/* Known error: CA can not determ if TA is launched or not, because framework is calling
	 * create entry point and open session function. Those functions return values is mapped
	 * into one return value. */
	if (interface->create() != TEE_SUCCESS) {
		OT_LOG(LOG_ERR, "TA create entry point failed");
		exit(EXIT_SUCCESS);
	}

	/* Launch worker thread and pass open session message as a parameter */
	ret = pthread_create(&ta_logic_thread, &attr, ta_internal_thread, open_msg);
	if (ret) {
		OT_LOG(LOG_ERR, "Failed launch thread: %s", strerror(errno))
		interface->destroy();
		exit(EXIT_FAILURE);
	}

	pthread_attr_destroy(&attr); /* Not needed any more */

	/* Allow signal delivery */
	if (pthread_sigmask(SIG_SETMASK, &sig_empty_set, NULL)) {
		OT_LOG(LOG_ERR, "failed to allow signals: %s", strerror(errno))
		exit(EXIT_FAILURE);
	}

	/* Enter into the main part of this io_thread */
	for (;;) {
		event_count = wrap_epoll_wait(cur_events, MAX_CURR_EVENTS);
//.........这里部分代码省略.........
开发者ID:z08053520,项目名称:TEE-Emu,代码行数:101,代码来源:ta_process.c


示例3: alder_kmer_thread7


//.........这里部分代码省略.........
                       uint8_t *inbuf,
                       size_t size_data,
                       struct bstrList *infile,
                       const char *outdir,
                       const char *outfile)
{
    alder_log5("preparing counting Kmers with version 2...");
    counter_id_counter = 0;
    counter_full_counter = 0;
    int s = 0;
    if (n_counter > 1 && kmer_size > 31) {
        mcas_init(n_counter);
    }
    
    alder_kmer_thread7_t *data =
    alder_kmer_thread7_create(fpout,
                              n_counter,
                              i_ni,
                              kmer_size,
                              memory_available,
                              sizeInbuffer,
                              sizeOutbuffer,
                              n_ni,
                              n_np,
                              n_nh,
                              lower_count,
                              *n_byte,
                              n_total_kmer,
                              *n_current_kmer,
                              progress_flag,
                              progressToError_flag,
                              nopack_flag,
                              infile,
                              outdir,
                              outfile);
    if (data == NULL) {
        alder_loge(ALDER_ERR_MEMORY, "failed to creat counter threads.");
        return ALDER_STATUS_ERROR;
    }
    alder_log5("creating %d threads: one for reader, and one for writer",
               n_counter);
    
    pthread_t *threads = malloc(sizeof(*threads)*n_counter);
    if (data == NULL || threads == NULL) {
        alder_loge(ALDER_ERR_MEMORY, "cannot create threads for counting");
        XFREE(threads);
        alder_kmer_thread7_destroy(data);
        return ALDER_STATUS_ERROR;
    }
    memset(threads,0,sizeof(*threads)*n_counter);
    
    pthread_attr_t attr;
    s += pthread_attr_init(&attr);
    s += pthread_mutex_init(&mutex_read, NULL);
    s += pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    for (int i = 0; i < n_counter; i++) {
        s += pthread_create(&threads[i], &attr, counter, (void *)data);
    }
    if (s != 0) {
        alder_loge(ALDER_ERR_THREAD, "cannot create threads - %s",
                   strerror(errno));
        goto cleanup;
    }
    
    /* Wait for all threads to complete */
    alder_log3("main(): waiting for all threads to complete...");
    for (int i = 0; i < n_counter; i++) {
        s += pthread_join(threads[i], NULL);
        if (s != 0) {
            alder_loge(ALDER_ERR_THREAD, "cannot join threads - %s",
                       strerror(errno));
            goto cleanup;
        }
    }
    
cleanup:
    /* Cleanup */
    pthread_attr_destroy(&attr);
    pthread_mutex_destroy(&mutex_read);
    XFREE(threads);
    
    data->n_byte = 0;
    for (int i = 0; i < n_counter; i++) {
        data->n_byte += data->n_i_byte[i];
    }
    data->n_kmer = 0;
    for (int i = 0; i < n_counter; i++) {
        data->n_kmer += data->n_i_kmer[i];
    }
    alder_log2("counter()[%d] Kmers: %zu", i_ni, data->n_kmer);
    alder_log2("counter()[%d) Bytes: %zu", i_ni, data->n_byte);
    *n_byte += data->n_byte;
    *n_kmer += data->n_kmer;
    *n_hash += data->n_hash;
    *n_current_kmer += data->n_kmer;
    
    alder_kmer_thread7_destroy(data);
    alder_log5("Counting Kmers has been finished with %d threads.", n_counter);
    return 0;
}
开发者ID:goshng,项目名称:cocoa,代码行数:101,代码来源:alder_kmer_thread7.c


示例4: do_test

static int
do_test (void)
{
  int n;
  pthread_t th[N];
  ucontext_t mctx;

  puts ("making contexts");
  if (getcontext (&mctx) != 0)
    {
      if (errno == ENOSYS)
	{
	  puts ("context handling not supported");
	  exit (0);
	}

      printf ("%s: getcontext: %m\n", __FUNCTION__);
      exit (1);
    }

  /* Play some tricks with this context.  */
  if (++global == 1)
    if (setcontext (&mctx) != 0)
      {
	puts ("setcontext failed");
	exit (1);
      }
  if (global != 2)
    {
      puts ("global not incremented twice");
      exit (1);
    }
  puts ("global OK");

  pthread_attr_t at;

  if (pthread_attr_init (&at) != 0)
    {
      puts ("attr_init failed");
      return 1;
    }

  if (pthread_attr_setstacksize (&at, 1 * 1024 * 1024) != 0)
    {
      puts ("attr_setstacksize failed");
      return 1;
    }

  for (n = 0; n < N; ++n)
    if (pthread_create (&th[n], &at, tf, (void *) (long int) n) != 0)
      {
	puts ("create failed");
	exit (1);
      }

  if (pthread_attr_destroy (&at) != 0)
    {
      puts ("attr_destroy failed");
      return 1;
    }

  for (n = 0; n < N; ++n)
    if (pthread_join (th[n], NULL) != 0)
      {
	puts ("join failed");
	exit (1);
      }

  return failures;
}
开发者ID:JamesLinus,项目名称:glibc-mips,代码行数:70,代码来源:tst-context1.c


示例5: main


//.........这里部分代码省略.........

	printf("Reuse Port %d: \tEnabled\n", port);
	fflush(stdout);

	memset((char *) &server_addr, '\0', sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(port);

	printf("Ip Address: \t\t%s\n", inet_ntoa(server_addr.sin_addr));
	fflush(stdout);

	/**
	 * Bind address.
	 */
	if ( (bind(server_socket, (struct sockaddr *) &server_addr, 
			sizeof(server_addr))) < 0 ) {
		server_error(strerror(errno), server_socket, l);
	}

	printf("Binding: \t\tSuccess\n");
	fflush(stdout);

	/**
	 * Listen on the server socket for connections
	 */
	if ( (listen(server_socket, 10)) < 0) {
		server_error(strerror(errno), server_socket, l);
	}

	printf("Listen: \t\tSuccess\n\n");
	fflush(stdout);

	/**
	 * Attributes for the threads we will create when a new client connects.
	 */
	pthread_attr_init(&pthread_attr);
	pthread_attr_setdetachstate(&pthread_attr, PTHREAD_CREATE_DETACHED);
	pthread_attr_setstacksize(&pthread_attr, 524288);

	printf("Server is now waiting for clients to connect ...\n\n");
	fflush(stdout);

	/**
	 * Create commandline, such that we can do simple commands on the server.
	 */
	if ( (pthread_create(&pthread_id, &pthread_attr, cmdline, NULL)) < 0 ){
		server_error(strerror(errno), server_socket, l);
	}

	/**
	 * Do not wait for the thread to terminate.
	 */
	pthread_detach(pthread_id);

	while (1) {
		client_length = sizeof(client_addr);
		
		/**
		 * If a client connects, we observe it here.
		 */
		if ( (client_socket = accept(server_socket, 
				(struct sockaddr *) &client_addr,
				&client_length)) < 0) {
			server_error(strerror(errno), server_socket, l);
		}

		/**
		 * Save some information about the client, which we will
		 * later use to identify him with.
		 */
		char *temp = (char *) inet_ntoa(client_addr.sin_addr);
		char *addr = (char *) malloc( sizeof(char)*(strlen(temp)+1) );
		if (addr == NULL) {
			server_error(strerror(errno), server_socket, l);
			break;
		}
		memset(addr, '\0', strlen(temp)+1);
	    memcpy(addr, temp, strlen(temp));	

		ws_client *n = client_new(client_socket, addr);

		/**
		 * Create client thread, which will take care of handshake and all
		 * communication with the client.
		 */
		if ( (pthread_create(&pthread_id, &pthread_attr, handleClient, 
						(void *) n)) < 0 ){
			server_error(strerror(errno), server_socket, l);
		}

		pthread_detach(pthread_id);
	}

	list_free(l);
	l = NULL;
	close(server_socket);
	pthread_attr_destroy(&pthread_attr);
	return EXIT_SUCCESS;
}
开发者ID:GangXu,项目名称:Websocket-1,代码行数:101,代码来源:Websocket.c


示例6: main


//.........这里部分代码省略.........
  timeout.tv_sec = duration / 1000;
  timeout.tv_nsec = (duration % 1000) * 1000000;

  if ((td = (thread_data_t *)malloc(nb_threads * sizeof(thread_data_t))) == NULL) {
    perror("malloc");
    exit(1);
  }
  if ((threads = (pthread_t *)malloc(nb_threads * sizeof(pthread_t))) == NULL) {
    perror("malloc");
    exit(1);
  }
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  for (i = 0; i < nb_threads; i++) {
    td[i].nb_aborts = 0;
    td[i].nb_aborts_1 = 0;
    td[i].nb_aborts_2 = 0;
    td[i].nb_aborts_locked_read = 0;
    td[i].nb_aborts_locked_write = 0;
    td[i].nb_aborts_validate_read = 0;
    td[i].nb_aborts_validate_write = 0;
    td[i].nb_aborts_validate_commit = 0;
    td[i].nb_aborts_invalid_memory = 0;
    td[i].nb_aborts_killed = 0;
    td[i].locked_reads_ok = 0;
    td[i].locked_reads_failed = 0;
    td[i].max_retries = 0;
    td[i].irrevocable_percent = irrevocable_percent;
    if (pthread_create(&threads[i], &attr, test, (void *)(&td[i])) != 0) {
      fprintf(stderr, "Error creating thread\n");
      exit(1);
    }
  }
  pthread_attr_destroy(&attr);
  nanosleep(&timeout, NULL);
  printf("STOPPING...\n");
  stop = 1;
  for (i = 0; i < nb_threads; i++) {
    if (pthread_join(threads[i], NULL) != 0) {
      fprintf(stderr, "Error waiting for thread completion\n");
      exit(1);
    }
  }

  printf("PASSED\n");
  printf("Number of successful irrevocable-serial executions   : %ld\n", nb_irrevocable_serial);
  printf("Number of successful irrevocable-parallel executions : %ld\n", nb_irrevocable_parallel);

  aborts = 0;
  aborts_1 = 0;
  aborts_2 = 0;
  aborts_locked_read = 0;
  aborts_locked_write = 0;
  aborts_validate_read = 0;
  aborts_validate_write = 0;
  aborts_validate_commit = 0;
  aborts_invalid_memory = 0;
  aborts_killed = 0;
  locked_reads_ok = 0;
  locked_reads_failed = 0;
  max_retries = 0;
  for (i = 0; i < nb_threads; i++) {
    printf("Thread %d\n", i);
    printf("  #aborts     : %lu\n", td[i].nb_aborts);
    printf("    #lock-r   : %lu\n", td[i].nb_aborts_locked_read);
    printf("    #lock-w   : %lu\n", td[i].nb_aborts_locked_write);
开发者ID:HPDCS,项目名称:stmEnergyOptimization,代码行数:67,代码来源:irrevocability.c


示例7: main

/******* web服务器程序入口函数 *******/
int main(int argc, char const *argv[])
{
	int    			   conn_sock;
	struct epoll_event ev;
	struct epoll_event events[MAXEVENTS];
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	socklen_t          addrlen;
	pthread_attr_t     pthread_attr_detach;
	_epollfd_connfd    epollfd_connfd;
	pthread_t          tid;

	if(argc != 2){
		printf("Usage: %s <config_path>\n", argv[0]);
		exit(-1);
	}
	//Is configure existed?
	if(-1 == going_is_file_existed(argv[1])){
		perror("going_is_file_existed.");
		exit(-1);
	}
	//parse configure
	if(-1 == going_parse_config(argv[1])){
		printf("going_parse_config error!\n");
		exit(-1);
	}

	//创建监听套接字
	int listen_fd = going_socket(AF_INET, SOCK_STREAM, 0);
	//设置监听套接字为非阻塞模式
	going_set_nonblocking(listen_fd);
	//对套接字设置SO_REUSEADDR选项
	going_set_reuse_addr(listen_fd);


	//通过服务名和协议名获得相应的知名端口
	//struct servent* pservent = going_getservbyname("http", "tcp");
	//uint16_t listen_port = pservent->s_port;
	
	uint16_t listen_port = 80;

	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = (listen_port);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	going_bind(listen_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
	going_listen(listen_fd, MAX_BACKLOG);

	// 创建epoll文件描述符
	int epollfd = going_epoll_create(MAXEVENTS);

	// 设置要处理的事件类型
	ev.events = EPOLLIN;
	// 设置与要处理的事件相关的文件描述符
	ev.data.fd = listen_fd;
	// 将监听事件加入epoll中
	going_epoll_add(epollfd, listen_fd, &ev);

	//设置线程属性为detach
	pthread_attr_init(&pthread_attr_detach);
	pthread_attr_setdetachstate(&pthread_attr_detach, PTHREAD_CREATE_DETACHED);

	for(;;){
		// 无限等待直到有描述符就绪
		int nfds = going_epoll_wait(epollfd, events, MAXEVENTS, -1);
		// 若going_epoll_wait被中断则重新调用该函数
		if(nfds == -1 && errno == EINTR)
			continue;

		for(int n = 0; n != nfds; ++n){
			// 处理监听套接字触发的事件
			if(events[n].data.fd == listen_fd){
				conn_sock = going_accept(listen_fd, (struct sockaddr *)&client_addr, &addrlen);
				// 设置新连接上的套接字为非阻塞模式
				going_set_nonblocking(conn_sock);
				// 设置读事件和ET模式
				ev.events = EPOLLIN | EPOLLET;
				ev.data.fd = conn_sock;
				// 将监听事件添加到epoll
				going_epoll_add(epollfd, conn_sock, &ev);
			}else{
				epollfd_connfd.epollfd = epollfd;
				epollfd_connfd.connfd = events[n].data.fd;
				ev.data.fd = conn_sock;
				// epoll不再监听这个事件
				going_epoll_del(epollfd, conn_sock, &ev);
				// 处理连接
				pthread_create(&tid, &pthread_attr_detach, &going_thread_func, (void *)&epollfd_connfd);
			}
		}
	}

	pthread_attr_destroy(&pthread_attr_detach);

	// 关闭监听描述符
	close(listen_fd);
	return 0;
}
开发者ID:tangwz,项目名称:Gogoing,代码行数:100,代码来源:http_core.cpp


示例8: DEBUG2

/*
 *	Spawn a new thread, and place it in the thread pool.
 *
 *	The thread is started initially in the blocked state, waiting
 *	for the semaphore.
 */
static THREAD_HANDLE *spawn_thread(time_t now)
{
	int rcode;
	THREAD_HANDLE *handle;
	pthread_attr_t attr;

	/*
	 *	Ensure that we don't spawn too many threads.
	 */
	if (thread_pool.total_threads >= thread_pool.max_threads) {
		DEBUG2("Thread spawn failed.  Maximum number of threads (%d) already running.", thread_pool.max_threads);
		return NULL;
	}

	/*
	 *	Allocate a new thread handle.
	 */
	handle = (THREAD_HANDLE *) rad_malloc(sizeof(THREAD_HANDLE));
	memset(handle, 0, sizeof(THREAD_HANDLE));
	handle->prev = NULL;
	handle->next = NULL;
	handle->thread_num = thread_pool.max_thread_num++;
	handle->request_count = 0;
	handle->status = THREAD_RUNNING;
	handle->timestamp = time(NULL);

	/*
	 *	Initialize the thread's attributes to detached.
	 *
	 *	We could call pthread_detach() later, but if the thread
	 *	exits between the create & detach calls, it will need to
	 *	be joined, which will never happen.
	 */
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	/*
	 *	Create the thread detached, so that it cleans up it's
	 *	own memory when it exits.
	 *
	 *	Note that the function returns non-zero on error, NOT
	 *	-1.  The return code is the error, and errno isn't set.
	 */
	rcode = pthread_create(&handle->pthread_id, &attr,
			request_handler_thread, handle);
	if (rcode != 0) {
		radlog(L_ERR, "Thread create failed: %s",
		       strerror(rcode));
		return NULL;
	}
	pthread_attr_destroy(&attr);

	/*
	 *	One more thread to go into the list.
	 */
	thread_pool.total_threads++;
	DEBUG2("Thread spawned new child %d. Total threads in pool: %d",
			handle->thread_num, thread_pool.total_threads);

	/*
	 *	Add the thread handle to the tail of the thread pool list.
	 */
	if (thread_pool.tail) {
		thread_pool.tail->next = handle;
		handle->prev = thread_pool.tail;
		thread_pool.tail = handle;
	} else {
		rad_assert(thread_pool.head == NULL);
		thread_pool.head = thread_pool.tail = handle;
	}

	/*
	 *	Update the time we last spawned a thread.
	 */
	thread_pool.time_last_spawned = now;

	/*
	 *	And return the new handle to the caller.
	 */
	return handle;
}
开发者ID:jmaimon,项目名称:freeradius-server,代码行数:87,代码来源:threads.c


示例9: handler

/*!
	\brief 'true' main of the program.

	It must be in a separate function because:
	- if we're in 'console' mode, we have to put the main thread waiting for a Ctrl+C
	(in order to be able to stop everything)
	- if we're in daemon mode, the main program must terminate and a new child must be 
	created in order to create the daemon

	\param ptr: it keeps the main socket handler (what's called 'sockmain' in the main() ), that
	represents the socket used in the main connection. It is a 'void *' just because pthreads
	want this format.
*/
void main_passive(void *ptr)
{
char errbuf[PCAP_ERRBUF_SIZE + 1];	// keeps the error string, prior to be printed
SOCKET sockctrl;				// keeps the socket ID for this control connection
struct sockaddr_storage from;	// generic sockaddr_storage variable
socklen_t fromlen;				// keeps the length of the sockaddr_storage variable
SOCKET sockmain;

#ifndef WIN32
	pid_t pid;
#endif

	sockmain= *((SOCKET *) ptr);

	// Delete the pointer (which has been allocated in the main)
	free(ptr);

	// Initialize errbuf
	memset(errbuf, 0, sizeof(errbuf) );

	// main thread loop
	while (1)
	{
#ifdef WIN32
	pthread_t threadId;					// Pthread variable that keeps the thread structures
	pthread_attr_t detachedAttribute;
#endif
	struct daemon_slpars *pars;			// parameters needed by the daemon_serviceloop()

		// Connection creation
		fromlen = sizeof(struct sockaddr_storage);

		sockctrl= accept(sockmain, (struct sockaddr *) &from, &fromlen);
		
		if (sockctrl == -1)
		{
			// The accept() call can return this error when a signal is catched
			// In this case, we have simply to ignore this error code
			// Stevens, pg 124
#ifdef WIN32
			if (WSAGetLastError() == WSAEINTR)
#else
			if (errno == EINTR)
#endif
				continue;

			// Don't check for errors here, since the error can be due to the fact that the thread 
			// has been killed
			sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE);
			SOCK_ASSERT(errbuf, 1);
			continue;
		}

		// checks if the connecting host is among the ones allowed
		if (sock_check_hostlist(hostlist, RPCAP_HOSTLIST_SEP, &from, errbuf, PCAP_ERRBUF_SIZE) < 0 )
		{
			rpcap_senderror(sockctrl, errbuf, PCAP_ERR_HOSTNOAUTH, NULL);
			sock_close(sockctrl, NULL, 0);
			continue;
		}


#ifdef WIN32
		// in case of passive mode, this variable is deallocated by the daemon_serviceloop()
		pars= (struct daemon_slpars *) malloc ( sizeof(struct daemon_slpars) );
		if (pars == NULL)
		{
			snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
			continue;
		}

		pars->sockctrl= sockctrl;
		pars->activeclose= 0;		// useless in passive mode
		pars->isactive= 0;
		pars->nullAuthAllowed= nullAuthAllowed;

		/* GV we need this to create the thread as detached. */
		/* GV otherwise, the thread handle is not destroyed  */
		pthread_attr_init(&detachedAttribute); 
		pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED);
		if ( pthread_create( &threadId, &detachedAttribute, (void *) &daemon_serviceloop, (void *) pars) )
		{
			SOCK_ASSERT("Error creating the child thread", 1);
			pthread_attr_destroy(&detachedAttribute);
			continue;
		}
		pthread_attr_destroy(&detachedAttribute);
//.........这里部分代码省略.........
开发者ID:CM44,项目名称:npcap,代码行数:101,代码来源:rpcapd.c


示例10: OverlapDriver


//.........这里部分代码省略.........

  //fprintf(stderr, "OverlapDriver()--  Loop top\n");

  while (bgnHashID < G.endHashID) {
    if (endHashID > G.endHashID)
      endHashID = G.endHashID;

    assert(0          <  bgnHashID);
    assert(bgnHashID  <= endHashID);
    assert(endHashID  <= gkpStore->gkStore_getNumReads());

    //  Load as much as we can.  If we load less than expected, the endHashID is updated to reflect
    //  the last read loaded.

    //fprintf(stderr, "OverlapDriver()--  Build_Hash_Index\n");

    endHashID = Build_Hash_Index(gkpStore, bgnHashID, endHashID);

    //fprintf(stderr, "Index built.\n");

    //  Decide the range of reads to process.  No more than what is loaded in the table.

    if (G.bgnRefID < 1)
      G.bgnRefID = 1;

    if (G.endRefID > gkpStore->gkStore_getNumReads())
      G.endRefID = gkpStore->gkStore_getNumReads();

    G.curRefID = G.bgnRefID;

    //  The old version used to further divide the ref range into blocks of at most
    //  Max_Reads_Per_Batch so that those reads could be loaded into core.  We don't
    //  need to do that anymore.

    G.perThread = 1 + (G.endRefID - G.bgnRefID) / G.Num_PThreads / 8;

    fprintf(stderr, "\n");
    fprintf(stderr, "Range: %u-%u.  Store has %u reads.\n",
            G.bgnRefID, G.endRefID, gkpStore->gkStore_getNumReads());
    fprintf(stderr, "Chunk: "F_U32" reads/thread -- (G.endRefID="F_U32" - G.bgnRefID="F_U32") / G.Num_PThreads="F_U32" / 8\n",
            G.perThread, G.endRefID, G.bgnRefID, G.Num_PThreads);

    fprintf(stderr, "\n");
    fprintf(stderr, "Starting "F_U32"-"F_U32" with "F_U32" per thread\n", G.bgnRefID, G.endRefID, G.perThread);
    fprintf(stderr, "\n");

    for (uint32 i=0; i<G.Num_PThreads; i++) {

      //  Initialize each thread, reset the current position.

      thread_wa[i].bgnID = G.curRefID;
      thread_wa[i].endID = thread_wa[i].bgnID + G.perThread - 1;

      G.curRefID = thread_wa[i].endID + 1;

      if (G.endRefID > G.endRefID)
        G.endRefID = G.endRefID;

      int status = pthread_create(thread_id+i, &attr, Process_Overlaps, thread_wa+i);

      if (status != 0)
        fprintf(stderr, "pthread_create error:  %s\n", strerror(status)), exit(1);
    }

    //  The master thread just sits here and waits.

    for (uint32 i=0; i<G.Num_PThreads; i++) {
      int status = pthread_join(thread_id[i], NULL);
      if (status != 0)
        fprintf(stderr, "pthread_join error: %s\n", strerror(status)), exit(1);
    }

    //  Clear out the hash table.  This stuff is allocated in Build_Hash_Index

    delete [] basesData;  basesData = NULL;
    delete [] qualsData;  qualsData = NULL;
    delete [] nextRef;    nextRef   = NULL;

    //  This one could be left allocated, except for the last iteration.

    delete [] Extra_Ref_Space;  Extra_Ref_Space = NULL;  Max_Extra_Ref_Space = 0;

    //  Prepare for another hash table iteration.
    bgnHashID = endHashID + 1;
    endHashID = bgnHashID + G.Max_Hash_Strings - 1;  //  Inclusive!
  }

  pthread_mutex_destroy(&Write_Proto_Mutex);
  pthread_attr_destroy(&attr);

  gkpStore->gkStore_close();

  for (uint32 i=0;  i<G.Num_PThreads;  i++)
    Delete_Work_Area(thread_wa + i);

  delete [] thread_wa;
  delete [] thread_id;

  return  0;
}
开发者ID:AndreasHegerGenomics,项目名称:canu,代码行数:101,代码来源:overlapInCore.C


示例11: main_startup

void main_startup(void)
{
char errbuf[PCAP_ERRBUF_SIZE + 1];	// keeps the error string, prior to be printed
struct addrinfo *addrinfo;				// keeps the addrinfo chain; required to open a new socket
int i;
#ifdef WIN32
	pthread_t threadId;					// Pthread variable that keeps the thread structures
	pthread_attr_t detachedAttribute;	// PThread attribute needed to create the thread as detached
#else
	pid_t pid;
#endif

	i= 0;
	addrinfo= NULL;
	memset(errbuf, 0, sizeof(errbuf) );

	// Starts all the active threads
	while ( (activelist[i].address[0] != 0) && (i < MAX_ACTIVE_LIST) )
	{
		activelist[i].ai_family= mainhints.ai_family;
		
#ifdef WIN32
		/* GV we need this to create the thread as detached. */
		/* GV otherwise, the thread handle is not destroyed  */
		pthread_attr_init(&detachedAttribute); 
		pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED);

		if ( pthread_create( &threadId, &detachedAttribute, (void *) &main_active, (void *) &activelist[i]) )
		{
			SOCK_ASSERT("Error creating the active child thread", 1);
			pthread_attr_destroy(&detachedAttribute);
			continue;
		}
		pthread_attr_destroy(&detachedAttribute);
#else
		if ( (pid= fork() ) == 0)	// I am the child
		{
			main_active( (void *) &activelist[i]);
			exit(0);
		}
#endif
		i++;
	}

	/*
		The code that manages the active connections is not blocking; 
		vice versa, the code that manages the passive connection is blocking.
		So, if the user do not want to run in passive mode, we have to block
		the main thread here, otherwise the program ends and all threads
		are stopped.

		WARNING: this means that in case we have only active mode, the program does
		not terminate even if all the child thread terminates. The user has always to
		press Ctrl+C (or send a SIGTERM) to terminate the program.
	*/

	if (passivemode)
	{
	struct addrinfo *tempaddrinfo;

		// Do the work
		if (sock_initaddress((address[0]) ? address : NULL, port, &mainhints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
		{
			SOCK_ASSERT(errbuf, 1);
			return;
		}

		tempaddrinfo= addrinfo;

		while (tempaddrinfo)
		{
		SOCKET *socktemp;

			if ( (sockmain= sock_open(tempaddrinfo, SOCKOPEN_SERVER, SOCKET_MAXCONN, errbuf, PCAP_ERRBUF_SIZE)) == -1)
			{
				SOCK_ASSERT(errbuf, 1);
				tempaddrinfo= tempaddrinfo->ai_next;
				continue;
			}

			// This trick is needed in order to allow the child thread to save the 'sockmain' variable
			// withouth getting it overwritten by the sock_open, in case we want to open more than one waiting sockets
			// For instance, the pthread_create() will accept the socktemp variable, and it will deallocate immediately that variable
			socktemp= (SOCKET *) malloc (sizeof (SOCKET));
			if (socktemp == NULL)
				exit(0);

			*socktemp= sockmain;

#ifdef WIN32
			/* GV we need this to create the thread as detached. */
			/* GV otherwise, the thread handle is not destroyed  */
			pthread_attr_init(&detachedAttribute); 
			pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED);

			if ( pthread_create( &threadId, &detachedAttribute, (void *) &main_passive, (void *) socktemp ) )
			{
				SOCK_ASSERT("Error creating the passive child thread", 1);
				pthread_attr_destroy(&detachedAttribute);
				continue;
//.........这里部分代码省略.........
开发者ID:CM44,项目名称:npcap,代码行数:101,代码来源:rpcapd.c


示例12: main

/*
The main program creates threads which do all the work and then 
print out the result upon completion. Before creating the threads, 
the input data is created. Since all threads update a shared structure, 
we need a mutex for mutual exclusion. The main thread need to wait for 
all threads to complete, it waits for each one of the threads. We specify 
a thread attribute value that allow the main thread to join with the threads 
it creates. Note also that we free up handles when they are no longer needed.
*/
int main(int argc, char *argv[])
{
	int i, ret, len;
	double *a, *b;
	void *status;
	pthread_attr_t attr;

	/* Assign storage and initialize values */
	len = VECLEN * NUMTHRDS;
	a = (double *) calloc (1, sizeof(double) * len);
	b = (double *) calloc (1, sizeof(double) * len);
	for (i = 0; i < len; ++i)
	{
		a[i] = 1;
		b[i] = a[i];
	}

	dotstr.veclen = VECLEN;
	dotstr.a = a;
	dotstr.b = b;
	dotstr.sum = 0;

	/* Create thread to perform the dotproduct */
	pthread_mutex_init(&mutexsum, NULL);
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	for (i = 0; i < NUMTHRDS; ++i)
	{
	/* Each thread works on a different set of data.
	 * The offset is specified by 'i'. The size of 
	 * the data for each thread is indicated by VECLEN.
	 */
		ret = pthread_create(thrd + i, &attr, dotprod, (void *)i);
		if (ret)
		{
			printf("ERROR; return code from pthread_create(): %d\r\n", ret);
			exit(-1);
		}
	}
	pthread_attr_destroy(&attr);

	/* Wait on the other threads */
	status = NULL;
	for (i = 0; i < NUMTHRDS; ++i)
	{
		ret = pthread_join(thrd[i], &status);
		if (ret)
		{
			printf("ERROR; return code from pthread_create(): %d\r\n", ret);
			exit(-1);
		}
	}

	/* After joining, print out the results and cleanup */
	printf("Sum = %.2lf\r\n", dotstr.sum);
	free(a);
	a = NULL;
	free(b);
	b = NULL;
	pthread_mutex_destroy(&mutexsum);
	pthread_exit(NULL);
}
开发者ID:chenpoyang,项目名称:icedy,代码行数:72,代码来源:mutex.c


示例13: do_test

static int
do_test (void)
{
  int result = 0;
  pthread_attr_t a;
  cpu_set_t c1, c2;

  int err = pthread_attr_init (&a);
  if (err)
    {
      error (0, err, "pthread_attr_init failed");
      result = 1;
    }

  err = pthread_attr_getaffinity_np (&a, sizeof (c1), &c1);
  if (err && err != ENOSYS)
    {
      error (0, err, "pthread_attr_getaffinity_np failed");
      result = 1;
    }

  err = pthread_attr_destroy (&a);
  if (err)
    {
      error (0, err, "pthread_attr_destroy failed");
      result = 1;
    }

  err = pthread_getattr_np (pthread_self (), &a);
  if (err)
    {
      error (0, err, "pthread_getattr_np failed");
      result = 1;
    }

  int detachstate;
  err = pthread_attr_getdetachstate (&a, &detachstate);
  if (err)
    {
      error (0, err, "pthread_attr_getdetachstate failed");
      result = 1;
    }
  else if (detachstate != PTHREAD_CREATE_JOINABLE)
    {
      error (0, 0, "initial thread not joinable");
      result = 1;
    }

  void *stackaddr;
  size_t stacksize;
  err = pthread_attr_getstack (&a, &stackaddr, &stacksize);
  if (err)
    {
      error (0, err, "pthread_attr_getstack failed");
      result = 1;
    }
  else if ((void *) &a < stackaddr
	   || (void *) &a >= stackaddr + stacksize)
    {
      error (0, 0, "pthread_attr_getstack returned range does not cover main's stack");
      result = 1;
    }
  else
    printf ("initial thread stack %p-%p (0x%zx)\n", stackaddr,
	    stackaddr + stacksize, stacksize);

  size_t guardsize;
  err = pthread_attr_getguardsize (&a, &guardsize);
  if (err)
    {
      error (0, err, "pthread_attr_getguardsize failed");
      result = 1;
    }
  else if (guardsize != 0)
    {
      error (0, 0, "pthread_attr_getguardsize returned %zd != 0",
	     guardsize);
      result = 1;
    }

  int scope;
  err = pthread_attr_getscope (&a, &scope);
  if (err)
    {
      error (0, err, "pthread_attr_getscope failed");
      result = 1;
    }
  else if (scope != PTHREAD_SCOPE_SYSTEM)
    {
      error (0, 0, "pthread_attr_getscope returned %d != PTHREAD_SCOPE_SYSTEM",
	     scope);
      result = 1;
    }

  int inheritsched;
  err = pthread_attr_getinheritsched (&a, &inheritsched);
  if (err)
    {
      error (0, err, "pthread_attr_getinheritsched failed");
      result = 1;
//.........这里部分代码省略.........
开发者ID:riscv,项目名称:riscv-glibc,代码行数:101,代码来源:tst-attr3.c


示例14: do_test

int
do_test (void)
{
  if (pthread_barrier_init (&b, NULL, N + 1) != 0)
    {
      puts ("barrier_init failed");
      exit (1);
    }

  if (sem_init (&s, 0, 0) != 0)
    {
      puts ("sem_init failed");
      exit (1);
    }

  struct sigaction sa;
  sa.sa_handler = handler;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = 0;
  if (sigaction (THE_SIG, &sa, NULL) != 0)
    {
      puts ("sigaction failed");
      exit (1);
    }

  pthread_attr_t a;

  if (pthread_attr_init (&a) != 0)
    {
      puts ("attr_init failed");
      exit (1);
    }

  if (pthread_attr_setstacksize (&a, 1 * 1024 * 1024) != 0)
    {
      puts ("attr_setstacksize failed");
      return 1;
    }

  int i;
  for (i = 0; i < N; ++i)
    if (pthread_create (&th[i], &a, tf, cbs[i]) != 0)
      {
	puts ("pthread_create failed");
	exit (1);
      }

  if (pthread_attr_destroy (&a) != 0)
    {
      puts ("attr_destroy failed");
      exit (1);
    }

  pthread_barrier_wait (&b);

  sigset_t ss;
  sigemptyset (&ss);
  sigaddset (&ss, THE_SIG);
  if (pthread_sigmask (SIG_BLOCK, &ss, NULL) != 0)
    {
      puts ("pthread_sigmask failed");
      exit (1);
    }

  /* Start sending signals.  */
  for (i = 0; i < TOTAL_SIGS; ++i)
    {
      if (kill (getpid (), THE_SIG) != 0)
	{
	  puts ("kill failed");
	  exit (1);
	}

      if (TEMP_FAILURE_RETRY (sem_wait (&s)) != 0)
	{
	  puts ("sem_wait failed");
	  exit (1);
	}

      ++nsigs;
    }

  pthread_barrier_wait (&b);

  for (i = 0; i < N; ++i)
    if (pthread_join (th[i], NULL) != 0)
      {
	puts ("join failed");
	exit (1);
      }

  return 0;
}
开发者ID:JamesLinus,项目名称:glibc-mips,代码行数:93,代码来源:tst-tls2.c


示例15: tf


//.........这里部分代码省略.........
  else
    {
      err = pthread_attr_getguardsize (ap, &guardsize2);
      if (err)
	{
	  error (0, err, "pthread_attr_getguardsize failed");
	  result = tf;
	}
      else if (guardsize1 != guardsize2)
	{
	  error (0, 0, "guardsize differs %zd != %zd",
		 guardsize1, guardsize2);
	  result = tf;
	}
      else
	printf ("thread guardsize %zd\n", guardsize1);
    }

  int scope1, scope2;
  err = pthread_attr_getscope (&a, &scope1);
  if (err)
    {
      error (0, err, "pthread_attr_getscope failed");
      result = tf;
    }
  else
    {
      err = pthread_attr_getscope (ap, &scope2);
      if (err)
	{
	  error (0, err, "pthread_attr_getscope failed");
	  result = tf;
	}
      else if (scope1 != scope2)
	{
	  error (0, 0, "scope differs %d != %d",
		 scope1, scope2);
	  result = tf;
	}
    }

  int inheritsched1, inheritsched2;
  err = pthread_attr_getinheritsched (&a, &inheritsched1);
  if (err)
    {
      error (0, err, "pthread_attr_getinheritsched failed");
      result = tf;
    }
  else
    {
      err = pthread_attr_getinheritsched (ap, &inheritsched2);
      if (err)
	{
	  error (0, err, "pthread_attr_getinheritsched failed");
	  result = tf;
	}
      else if (inheritsched1 != inheritsched2)
	{
	  error (0, 0, "inheritsched differs %d != %d",
		 inheritsched1, inheritsched2);
	  result = tf;
	}
    }

  cpu_set_t c1, c2;
  err = pthread_getaffinity_np (pthread_self (), sizeof (c1), &c1);
  if (err == 0)
    {
      err = pthread_attr_getaffinity_np (&a, sizeof (c2), &c2);
      if (err)
	{
	  error (0, err, "pthread_attr_getaffinity_np failed");
	  result = tf;
	}
      else if (memcmp (&c1, &c2, sizeof (c1)))
	{
	  error (0, 0, "pthread_attr_getaffinity_np returned different CPU mask than pthread_getattr_np");
	  result = tf;
	}
    }

  err = pthread_attr_destroy (&a);
  if (err)
    {
      error (0, err, "pthread_attr_destroy failed");
      result = tf;
    }

  if (ap == &a2)
    {
      err = pthread_attr_destroy (ap);
      if (err)
	{
	  error (0, err, "pthread_attr_destroy failed");
	  result = tf;
	}
    }

  return result;
}
开发者ID:riscv,项目名称:riscv-glibc,代码行数:101,代码来源:tst-attr3.c


示例16: main


//.........这里部分代码省略.........
        flush_interval = atoi(optarg);
        printf("Flush interval set to %d seconds.\n", flush_interval);
        break;
      case 'p':
        port = atoi(optarg);
        printf("Statsd port set to %d\n", port);
        break;
      case 'm':
        mgmt_port = atoi(optarg);
        printf("Management port set to %d\n", mgmt_port);
        break;
      case 's':
        serialize_file = strdup(optarg);
        printf("Serialize to file %s\n", serialize_file);
        break;
      case 'c':
        clear_stats = 1;
        printf("Clearing stats on start.\n");
        break;
      case 'G':
        ganglia_host = strdup(optarg);
        enable_gmetric = 1;
        printf("Ganglia host %s\n", ganglia_host);
        break;
      case 'g':
        ganglia_port = atoi(optarg);
        printf("Ganglia port %d\n", ganglia_port);
        break;
      case 'S':
        ganglia_spoof = strdup(optarg);
        printf("Ganglia spoof host %s\n", ganglia_spoof);
        break;
      case 'P':
        ganglia_metric_prefix = strdup(optarg);
        printf("Ganglia metric prefix %s\n", ganglia_metric_prefix);
        break;
      case 'l':
        lock_file = strdup(optarg);
        printf("Lock file %s\n", lock_file);
        break;
      case 'h':
      default:
        syntax(argv);
        break;
    }
  }

  if (ganglia_spoof == NULL) {
    ganglia_spoof = strdup("statsd:statsd");
  }

  if (debug) {
    setlogmask(LOG_UPTO(LOG_DEBUG));
    openlog("statsd-c",  LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
  } else {
    setlogmask(LOG_UPTO(LOG_INFO));
    openlog("statsd-c", LOG_CONS, LOG_USER);
  }

  /* Initialization of certain stats, here. */
  init_stats();

  if (daemonize) {
    syslog(LOG_DEBUG, "Daemonizing statsd-c");
    daemonize_server();

    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 1024 * 1024);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  }

  pthread_create (&thread_udp,   daemonize ? &attr : NULL, (void *) &p_thread_udp,   (void *) &pids[0]);
  pthread_create (&thread_mgmt,  daemonize ? &attr : NULL, (void *) &p_thread_mgmt,  (void *) &pids[1]);
  pthread_create (&thread_flush, daemonize ? &attr : NULL, (void *) &p_thread_flush, (void *) &pids[2]);
  pthread_create (&thread_queue, daemonize ? &attr : NULL, (void *) &p_thread_queue, (void 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ pthread_attr_getschedparam函数代码示例发布时间:2022-05-30
下一篇:
C++ pthread_atfork函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap