Search⌘ K
AI Features

Initialize Threads with std::call_once

Explore how to use std::call_once with std::once_flag to guarantee that initialization code runs exactly once, even across multiple threads. Understand thread synchronization and how to apply these C++20 concurrency features to safely manage shared resources.

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:

constexpr size_t max_threads{ 25 };

We also need a std::once_flag to synchronize the ...