skip to content

In C++, how does std::call_once with a std::once_flag initialize shared data exactly once, and what happens if the initializer throws?

level: middleimportance: should knowfreq 40%

answer

  1. a flag plus a callable
  2. active and passive executions
  3. one returning execution at most
  4. a throw lets the next caller retry

basics

~20 s

std::call_once(flag, f) lets one caller at a time run f until a run returns normally; other callers wait, and every later call returns without running f but sees its results. If f throws, that caller gets the exception and a later call retries.

solid answer

~40 s

A `std::once_flag` records whether a callable has completed. `std::call_once(flag, f, args...)` either runs `f` (an *active* execution) or returns without running it (a *passive* execution). Active executions on one flag happen in a total order, so concurrent callers wait. At most one execution is *returning*, the one that completes normally, and it synchronizes with every passive call, so all threads see the data it initialized without further locking. If `f` throws, the execution is *exceptional*: the exception propagates to that caller and does not count, so the next caller runs `f` again, which suits transient failures such as a busy index file. For a single object, a function-local `static` gives the same once-only, retry-on-throw initialization with less code; `std::call_once` fits when the lazily initialized state is a member or several globals.

code

cpp · 30 lines
cpp
#include <iostream>
#include <map>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>

std::once_flag index_once;
std::map<std::string, int> location_index;   // sku -> aisle
int load_attempts = 0;

void load_index() {
    if (++load_attempts == 1)
        throw std::runtime_error("index file busy");   // exceptional execution
    location_index = {{"bolt-m8", 12}, {"nut-m8", 13}};
}

int aisle_of(const std::string& sku) {
    std::call_once(index_once, load_index);   // returning execution happens once
    return location_index.at(sku);
}

int main() {
    try { aisle_of("bolt-m8"); }
    catch (const std::exception& e) { std::cout << "first call: " << e.what() << '\n'; }
    std::thread a([] { aisle_of("bolt-m8"); }), b([] { aisle_of("nut-m8"); });
    a.join();
    b.join();
    std::cout << "aisle " << aisle_of("nut-m8") << ", load attempts " << load_attempts << '\n';
}

go deeper

for a junior

Know that std::call_once with a std::once_flag runs a function exactly once even when many threads call it.

for a middle

Explain active, passive and exceptional executions and why passive callers see the initialized data without a lock.

for a senior

Choose between call_once and a function-local static, handle a failing initializer, and avoid local flags and re-entry.

for a principal

Decide where lazy initialization is allowed in a service at all versus explicit startup ordering.

## The problem it solves A warehouse service keeps a location index, SKU to aisle, that is expensive to load and needed by many threads. Loading it at startup slows every start; loading it lazily raises two questions: which thread loads it, and how do the others know it is ready? A plain `bool loaded` checked without a lock is a data race. Double-checked locking with a plain flag is the classic broken fix. `std::call_once` is the library's correct answer. ## The pieces - `std::once_flag` is an opaque, non-copyable object. Its `constexpr` default constructor puts it in the "nothing has been called" state, so a namespace-scope `once_flag` is constant-initialized and safe to use from any thread. - `std::call_once(flag, f, args...)` invokes `f` with the arguments, as `INVOKE` would, or not at all, depending on the flag. The standard describes the behaviour in terms of executions: | Execution | Calls `f`? | Outcome | |---|---|---| | **active, returning** | yes | `f` returns normally; the flag is now set | | **active, exceptional** | yes | `f` throws; the exception propagates to this caller; the flag stays unset | | **passive** | no | returns, seeing everything the returning execution did | For any one flag, **at most one** execution is returning, it is the **last** active execution, and passive executions exist only if a returning one does. ## Synchronization guarantees Two rules make the pattern safe: 1. All active executions on a flag happen in a **total order**, and the completion of each synchronizes with the start of the next. Concurrent first callers therefore queue rather than running `f` in parallel. 2. The returning execution **synchronizes with the return from every passive execution**. Whatever `f` wrote is visible to every thread whose `call_once` returned, without another lock. The second rule covers only data written **inside** `f`. Later modifications of the same data still need their own synchronization. ## Exceptions and retry If the index file is locked by a backup job, `load_index` throws. That caller sees the exception; the flag is not set; the next caller of `aisle_of` runs `load_index` again. The example below shows exactly this: the first call fails, a later call succeeds, and the loader ran twice in total. Callers must be prepared for the exception, and a permanently failing initializer will be retried on every call, so add backoff or a failure state if retrying is expensive. ## call_once versus a function-local static Since C++11, the dynamic initialization of a block-scope `static` happens the first time control passes its declaration; concurrent callers wait for it, and if the initializer throws, initialization is tried again on the next entry. That gives the same guarantees with no flag: ```cpp const LocationIndex& index() { static const LocationIndex idx = load_index_from_disk(); return idx; } ``` Prefer the static for a single object owned by one function. Use `std::call_once` when: - the state is a **class member**, so each object needs its own `once_flag`; - the initialization sets **several** variables, not one object; - the initializer needs arguments that are only known at the call site. ## A per-object flag When each object initializes its own cache lazily, the flag is a member: ```cpp class BinCatalog { mutable std::once_flag loaded_; mutable std::vector<Bin> bins_; void load() const; public: const std::vector<Bin>& bins() const { std::call_once(loaded_, [this] { load(); }); return bins_; } }; ``` A function-local `static` would be shared by every `BinCatalog`, which is wrong here. Note the consequence for the class: `std::once_flag` is not copyable, so `BinCatalog` is no longer copyable either. ## Pitfalls - A `std::once_flag` that is a local variable of the calling function is a new flag on every call, so the callable runs every time. - Calling `std::call_once` on the same flag from inside `f` waits on an initialization that cannot finish, and in practice deadlocks; do not re-enter. - `once_flag` cannot be copied or moved, so a class holding one is non-copyable unless you write the copy yourself. - Code that only needs a constant should use `constexpr` or `constinit` and skip run-time initialization altogether.

  • Why does a std::once_flag declared as a local variable not work?
    Each call of the function constructs a fresh `once_flag` in the "nothing called" state, so every call is an active execution and runs the callable again. The flag must outlive all the calls it coordinates: a namespace-scope object, a `static` local, or a member of the object whose state it guards.
  • When would you choose std::call_once over a function-local static?
    When the lazily initialized state is a non-static class member, so each object needs its own flag; when one initialization sets several variables rather than producing one object; or when the initializer needs arguments from the call site. For a single object returned from a function, the static is shorter and gives the same once-only and retry-on-throw guarantees.

  • If the callable throws, std::call_once marks the flag done and never retries.
  • Two threads calling std::call_once at the same moment may both run the callable.
  • Threads that skip the callable still need a mutex to read what it initialized.
  • A std::once_flag can be a local variable inside the function that calls std::call_once.
  • A checked bool flag without a lock is just as safe as std::call_once.