Thread-Safe Initialization: call_once and once_flag

This lesson gives an overview of thread-safe initialization in the perspective of concurrency in C++.

By using the std::call_once function you can register a callable. The std::once_flag ensures that only one registered function will be invoked, but you can register additional functions via the same std::once_flag. That being said, only one function from that group is called.

std::call_once obeys the following rules:

  • Exactly one execution of exactly one of the functions is performed. It is undefined which function will be selected for execution. The selected function runs in the same thread as the std::call_once invocation it was passed to.
  • No invocation in the group returns before the above-mentioned execution of the selected function completes successfully.
  • If the selected function exits via an exception, it is propagated to the caller. Another function is then selected and executed.

The short example demonstrates the application of std::call_once and the std::once_flag. Both of them are declared in the header <mutex>.

Get hands-on with 1400+ tech skills courses.