std::call_once (3) - Linux Manuals
std::call_once: std::call_once
NAME
std::call_once - std::call_once
Synopsis
Defined in header <mutex>
template< class Callable, class... Args > (since C++11)
void call_once( std::once_flag& flag, Callable&& f, Args&&... args );
Executes the Callable object f exactly once, even if called concurrently, from several threads.
In detail:
* If, by the time call_once is called, flag indicates that f was already called, call_once returns right away (such a call to call_once is known as passive).
* Otherwise, call_once invokes std::forward<Callable>(f) with the arguments std::forward<Args>(args)... (as if by std::invoke). Unlike the std::thread constructor or std::async, the arguments are not moved or copied because they don't need to be transferred to another thread of execution. (such a call to call_once is known as active).
All active calls on the same flag form a single total order consisting of zero or more exceptional calls, followed by one returning call. The end of each active call synchronizes-with the next active call in that order.
The return from the returning call synchronizes-with the returns from all passive calls on the same flag: this means that all concurrent calls to call_once are guaranteed to observe any side-effects made by the active call, with no additional synchronization.
Parameters
flag - an object, for which exactly one function gets executed
f - Callable object to invoke
args... - arguments to pass to the function
Return value
(none)
Exceptions
* std::system_error if any condition prevents calls to call_once from executing as specified
* any exception thrown by f
Notes
If concurrent calls to call_once pass different functions f, it is unspecified which f will be called. The selected function runs in the same thread as the call_once invocation it was passed to.
Initialization of function-local_statics is guaranteed to occur only once even when called from multiple threads, and may be more efficient than the equivalent code using std::call_once.
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
LWG_2442 C++11 the arguments are copied and/or moved before invocation no copying/moving is performed
Example
// Run this code
Possible output:
See also
once_flag helper object to ensure that call_once invokes the function only once
(C++11)