Thread-Safe Initialization of Data
If the variable is never modified there is no need for synchronization by using an expensive
lock or an
atomic. We must ensure that it is initialized in a thread-safe way.
There are four ways in C++ to initialize variables in a thread-safe way.
- Constant expressions.
- The function
std::call_oncein combination with the flag
- A static variable with block scope.
🔑 Thread-safe initialization in the main-thread
The easiest and fourth way to initialize a variable in a thread-safe way: initialize the variable in the main-thread before we create any child threads.
Constant expressions can be evaluated by the compiler at compile time. They are implicitly thread-safe. Placing the keyword
constexpr in front of a variable makes the variable a constant expression. This constant expression must be initialized immediately.