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. 这篇关于如何唤醒休眠线程并退出主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 05:47