C++ Reference ยท Concurrency
C++ std::call_once and std::once_flag
Reference for std::call_once and std::once_flag: run initialization code exactly once across threads, handle exceptions, and compare with function-local statics.
std::call_once (header <mutex>) runs a callable exactly once, no matter how many threads call it with the same std::once_flag. The first caller runs the function; any other thread that arrives meanwhile blocks until it finishes; later callers return immediately. When call_once returns, the initialization is complete and its effects are visible to the calling thread.
It is the tool for lazy, thread-safe, one-time setup of something that does not fit a plain function-local static (for example a member that is created on first use, or initialization that depends on arguments).
std::once_flag flag; void init() { /* expensive setup */ } void use() { std::call_once(flag, init); // safe to call from any thread, any number of times }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
If the callable throws, the exception reaches the caller of call_once, the flag stays unset and the next call tries again. The next snippet is read-only because it hangs on our runner (GCC 15.2 with a static libstdc++ build): a throwing call_once never returns there, so do not rely on this path in code you test here. On a normal dynamically linked toolchain it behaves as the standard describes.
std::once_flag flag; int attempts = 0; void risky() { if (++attempts < 3) { throw std::runtime_error("not ready yet"); // flag stays unset } } // calls 1 and 2 throw; call 3 succeeds; call 4 does nothing
Syntax
struct once_flag { constexpr once_flag() noexcept; once_flag(const once_flag&) = delete; once_flag& operator=(const once_flag&) = delete; }; template<class Callable, class... Args> void call_once(std::once_flag& flag, Callable&& f, Args&&... args);
| Name | Description |
|---|---|
flag |
The object that remembers whether initialization has happened. Must be shared by all callers. |
f |
The callable to run once. |
args... |
Arguments forwarded to f (copied or moved, like std::thread). |
Returns: nothing. Errors: if f throws, the exception propagates to the caller of call_once, the flag is not set, and another call will try again (this is called an exceptional execution). std::system_error may be thrown if the platform cannot do the synchronization.
Usage notes
- Same flag for all callers. Each distinct piece of one-time work needs its own
once_flag; aonce_flagcannot be copied or moved, so keep it as a global, astatic, or a class member. - Function-local statics are often simpler.
static const Config c = load();is also initialized exactly once, thread-safely, since C++11. Usecall_oncewhen the initialization needs arguments, is conditional, or targets a member. - Recursive use deadlocks. Calling
call_oncewith the same flag from inside its own callable never completes. - Visibility: the completion of the initialization synchronizes-with every
call_oncereturn, so data written byfis safe to read afterwards without extra locking. - No way to reset a flag. If you need re-initialization, use a mutex-protected pointer.
- Cost: after the first run, a
call_oncecosts about one atomic load.