Daily bit(e) of C++ | std::call_once
Daily bit(e) of C++ ♻️33, Guaranteeing a single invocation of a callable across multiple concurrent calling sites using: std::call_once.
The std::call_once is a low-level synchronization tool that guarantees a single successful call (i.e. a call that doesn't throw) to a callable.
Each call attempt (with the same flag) synchronizes with the exit of the previous attempt, and the exit of the successful call synchronizes with all concurrent calls, making any state changes visible to all threads without additional synchronization.
Note that if the synchronization is localized in a single function, a local static variable provides the same guarantees for its initialization. The std::call_once can be used to synchronize across multiple functions.