Thread-Safe Initialization of Data

In this lesson, we will learn about the three ways for 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_once in combination with the flag std::once_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

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.

Get hands-on with 1400+ tech skills courses.