Initialize threads with std::call_once
You may need to run the same code in many threads but must initialize that code only once.
One solution would be to call the initialization code before running the threads. This approach can work but has some drawbacks. By separating the initialization, it may be called when unnecessary, or it may be missed when necessary.
The std::call_once
function provides a more robust solution. call_once
is in the <mutex>
header.
How to do it…
In this recipe, we use a print function for the initialization, so we can clearly see when it's called:
- We'll use a constant for the number of threads to spawn:
constexpr size_t max_threads{ 25 };
We also need a std::once_flag
to synchronize the std::call_once
function:
std::once_flag init_flag;
- Our initialization function simply prints a string to let us know it's been called:
void do_init(size_t id) { cout << format("...