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?
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
InterlockedIncrementit at the beginning of a thread, thenInterlockedDecrementit 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
ResetEventwhen the thread starts andSetEventwhen it finishes. Then justWaitForMultipleObjectsfor all events.