The std::thread designed to perform exactly one task (the one you give it in the constructor), and then ends. If you want to do more work, you will need a new thread. Starting with C ++ 11, that's all we have. Thread pools are not standard. (I'm not sure what C ++ 14 can say about them.)
Fortunately, you can easily implement the required logic yourself. Here is a large-scale picture:
- Run n workflows that all do the following:
- Repeat until there is more work:
- Take the following task t (possibly until it is ready).
- Process t.
- Continue to insert new tasks into the processing queue.
- Tell workflows that thereโs nothing more to do.
- Wait for the workflow to complete.
The hardest part here (which is still pretty simple) is correctly designing the work queue. Usually for this there will be a synchronized linked list (from STL). Synchronized means that any thread that wants to manage the queue should only do this after it has acquired std::mutex to avoid race conditions. If the workflow finds the list empty, it must wait until there is some work. You can use std::condition_variable for this. Each time a new task is inserted into the queue, the inserting thread notifies the thread that is waiting for the condition variable, and therefore stops the lock and eventually starts processing the new task.
The second not-so-trivial part is how to signal workflows what no longer needs to be done. It is clear that you can set some global flag, but if the worker is blocked in the queue, it will not be implemented in the near future. One solution could be to stream notify_all() and check the flag every time they are notified. Another option is to queue up several โtoxicโ items. If a worker encounters this item, it exits.
The representation of the task queue is done directly using your self- task objects or just lambda.
All of the above features are C ++ 11. If you stick to an earlier version, you need to go to third-party libraries that provide multithreading for your specific platform.
While none of them is rocket science, for the first time itโs still easy to make a mistake. And, unfortunately, concurrency-related errors are some of the most difficult to debug. Starting from several hours of reading through the appropriate sections of a good book or working through a textbook, you can quickly pay off.
5gon12eder
source share