Wait for tasks to get completed in threadpool

2019-06-24 10:36发布

问题:

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.