等待线程池中的任务完成
我用 C++ 创建了一个线程池,它将所有任务存储在队列中。线程池启动 n 个线程,从队列中获取任务,处理每个任务,然后从队列中删除任务。
现在,我想等到所有任务完成。检查空队列以完成任务可能不起作用,因为可以将任务分配给每个线程并且队列可以被清空,但任务仍然可以处于处理模式。
我不知道如何等待所有任务完成。这是一个设计问题。有什么建议吗?
I have created a thread pool in C++ which stores all tasks in a queue. Thread pool start n number of threads which takes tasks from queue , process each task and then delete tasks from queue.
Now , I want to wait till all tasks get completed. Checking for empty queue for completion of tasks may not work as , task can be given to each thread and queue can be emptied but still the tasks can in processing mode.
I am not getting idea how to wait for all the tasks completion.This is a design problem. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要等待所有线程完成,还是只需要检查?
如果您只需要检查,可以使用一个变量来存储当前正在执行的任务的数量,并在线程开始处使用 InterlockedIncrement ,然后在线程的末尾使用 InterlockedDecrement 。结尾。
如果您需要等待,并且线程数量较少,则每个线程都可以有自己的手动重置事件,您可以在线程启动时使用
ResetEvent
,在线程结束时使用SetEvent
。然后只需WaitForMultipleObjects
处理所有事件。Do you need to wait for all threads to finish, or do you just need to check?
If you just need to check, you can have a variable that stores the number of currently executing tasks, and
InterlockedIncrement
it at the beginning of a thread, thenInterlockedDecrement
it at the end.If you need to wait, and you have a small number of threads, each thread can have its own manual reset event that you
ResetEvent
when the thread starts andSetEvent
when it finishes. Then justWaitForMultipleObjects
for all events.使用告诉处理线程退出的哨兵任务。将 n 个任务放入队列中。然后加入你的线程池。
显然,您可以修改它,这样您就可以执行一些操作来保持池处于活动状态,而不是使用退出/加入进行同步。例如,每个线程在使哨兵任务出队时可以在某种条件变量或屏障或计数信号量上进行同步。
Use a sentinal task that tells the processing thread to exit. Put n of these tasks on the queue. Then join your thread pool.
You can obviously modify this so that rather than using exit/join for synchronization, you can do something that keeps the pool alive. For instance, each thread can syncrhonize on some kind of conditional variable or barrier or counting semaphore when it dequeues a sentinal task.