If the variable is never modified there is no need for synchronization by using an expensive lock or an atomic. You only have to ensure that it is initialized in a thread-safe way.
There are three 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 initialisation in the main-thread
The easiest and fourth way to initialise a variable in a thread-safe way: initialise the variable in the main-thread before you create any child threads.
We will explain each thread-safe initialization method in the next 3 lessons.