如何唤醒休眠线程并退出主线程?

How to wake the sleeping threads and exit the main thread?

我正在创建 10 个线程。每个线程都会做一些任务。有7个任务要完成。由于任务数少于线程数,因此总会有 3 个线程处于休眠状态,什么都不做。

我的主线程必须等待任务完成并仅在所有任务完成时退出(即当线程退出时)。我在 for 循环中等待并调用 pthread_join 但是有 3 个线程正在休眠,我怎样才能唤醒它们并让它们退出?

这是我现在正在做的事情。

// thread handler function, called when the thread is created
void* handler_func(void* arg) {
  while(true){
       pthread_mutex_lock(&my_queue_mutex);
           while(my_queue_is_empty()) {
                 pthread_cond_wait(&my_cond_var, &my_queue_mutex);
           }
           item = get_item_from_queue();
       pthread_mutex_unlock(&my_queue_mutex);
   }   
  pthread_exit(NULL);
}

int total_threads_to_create = 10;
int total_requests_to_make = 7;
pthread_t threads[total_threads_to_create];


for(int i = 0; i < total_threads_to_create; i++) {
     // create threads
     pthread_create(&threads[i], NULL, handler_func, NULL);

}

for(int i=0;i<total_requests_to_make;i++){
      // fill up the task queue
      add_task_to_my_queue(i + 100);

}



for(int i = 0; i< total_threads_to_create; i++) {
       // wait for threads to finish
       pthread_join(threads[i], NULL);
}

最简单的做法是将指示 "all done" 的虚拟任务排队给工人,因为您事先知道工人的数量:

for(int i=0;i<total_threads_to_create;i++){
  // a task of -1 means "no more work"
  add_task_to_my_queue(-1);
}

或者,您可以有一个 "breakable" 队列。该队列使用复合谓词唤醒等待中的消费者:非空 已完成。 Perl 的 Thread::Queue 对象可以是 ended, for example, and Python's queues can track completed tasks.

另一种选择是跟踪自己完成的任务数,使用自己的条件变量和互斥锁或 "countdown latch" 或其他任何东西,而不关心工作线程。它们会在程序退出时蒸发。