Initialize Threads with std::call_once

Learn to initialize threads with std::call_once.

We'll cover the following

We 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:

Get hands-on with 1200+ tech skills courses.