如何唤醒休眠线程并退出主线程? [英] How to wake the sleeping threads and exit the main thread?
问题描述
我正在创建 10 个线程.每个线程都会做一些任务.有7个任务要完成.由于任务数小于线程数,因此总会有 3 个线程处于休眠状态并且什么也不做.
I am creating 10 threads. Each thread will do some task. There are 7 tasks to be done. Since number of tasks are less than the number of threads, there would always be 3 threads that sleep and do nothing.
我的主线程必须等待任务完成并只有在所有任务完成时(即线程退出时)才退出.我在 for 循环中等待并调用 pthread_join
但是有 3 个线程正在休眠,我该如何唤醒它们并使它们退出?
My main thread must wait for the tasks to get completed and exit only when all the tasks are done (i.e when the thread exits). I am waiting in a for loop and calling pthread_join
but with the 3 threads that are sleeping, how can I wake them up and make them exit?
这就是我现在正在做的事情.
Here is what I am doing now.
// 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);
}
推荐答案
最简单的做法是将向工作人员表示全部完成"的虚拟任务加入队列,因为您事先知道工作人员的数量:>
The simplest thing to do would be to enqueue dummy tasks that indicate "all done" to the workers, since you know the number of workers in advance:
for(int i=0;i<total_threads_to_create;i++){
// a task of -1 means "no more work"
add_task_to_my_queue(-1);
}
或者,您可以拥有一个易碎"队列.这个队列用一个复合谓词唤醒等待的消费者:非空或完成.例如,Perl 的 Thread::Queue 对象可以结束,Python 的队列可以跟踪已完成的任务.
Alternatively, you can have a "breakable" queue. This queue wakes up waiting consumers with a compound predicate: either non-empty or finished. Perl's Thread::Queue objects can be ended, for example, and Python's queues can track completed tasks.
另一种选择是跟踪自己完成的任务数量,使用自己的条件变量和互斥锁或倒计时锁存器"或其他什么,而不关心工作线程.当程序退出时,它们会被蒸发掉.
Another option would be to keep track of the number of tasks completed yourself, with its own condition variable and mutex or a "countdown latch" or whatever, and not care about the worker threads. They'll be vaporized when the program exits.
这篇关于如何唤醒休眠线程并退出主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!