Wait for tasks to get completed in threadpool

一世执手 提交于 2019-12-23 15:11:22

问题


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?


回答1:


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, then InterlockedDecrement 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 and SetEvent when it finishes. Then just WaitForMultipleObjects for all events.




回答2:


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.



来源:https://stackoverflow.com/questions/4571225/wait-for-tasks-to-get-completed-in-threadpool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!