skip to content

In C++, when is a function-local static variable initialized, and what happens when two threads reach it at once?

level: middleimportance: must knowfreq 68%

answer

  1. first pass through the declaration
  2. once, even with many threads
  3. a guard checked on every call
  4. a throwing initializer is retried

basics

~20 s

A function-local static with dynamic initialization is initialized the first time control passes through its declaration, and only once. Since C++11 a second thread arriving meanwhile waits for it to finish; if the initializer throws, the next call tries again.

solid answer

~40 s

If the initializer of a block-scope `static` is a constant expression, the variable is **constant-initialized** before any code runs. Otherwise it is **dynamically initialized** the first time control passes through its declaration, and it counts as initialized only when that initializer completes. Since C++11 the standard says a thread that enters the declaration while another is initializing it **waits** for that initialization to finish, so the constructor runs exactly once without a `std::mutex` or `std::call_once`. If the initializer throws, initialization is incomplete and the **next** call tries again. Re-entering the declaration recursively during its own initialization is undefined behaviour. Compilers implement this with a guard variable checked on every call; on Itanium-ABI platforms the slow path calls `__cxa_guard_acquire` and `__cxa_guard_release`, and GCC and Clang's `-fno-threadsafe-statics` removes that locking.

code

cpp · 20 lines
cpp
#include <cstdio>
#include <stdexcept>
int attempts = 0;
struct Config {
  Config() {
    ++attempts;
    std::printf("Config() attempt %d\n", attempts);
    if (attempts == 1) throw std::runtime_error("disk not ready");
  }
};
Config& config() {
  static Config instance;  // initialized the first time control passes here
  return instance;
}
int main() {
  try { config(); } catch (const std::exception& e) { std::printf("caught: %s\n", e.what()); }
  config();
  config();
  std::printf("constructor ran %d times\n", attempts);
}

go deeper

for a junior

Recall that a static local is built the first time the function runs past it and then keeps its value across calls.

for a middle

Explain the C++11 guarantee: one initialization, concurrent callers wait, a throwing initializer is retried, and recursive re-entry is undefined behaviour.

for a senior

Discuss the guard check on every call, the Itanium ABI guard functions, logic deadlocks inside initializers, and when -fno-threadsafe-statics is safe to use.

for a principal

Decide where lazy function-local statics are acceptable in a codebase versus constinit data or explicit initialization from main, weighing hidden first-call latency against ordering safety.

## First pass through the declaration A **function-local static** (the standard says a *block variable with static storage duration*) has storage for the whole program, but its object is built lazily. Two cases: - If its initializer is a **constant expression**, the variable is constant-initialized as part of static initialization, before any dynamic initialization runs. Nothing happens at the call site. - Otherwise it is **dynamically initialized** the first time control passes through its declaration. Until then it holds only zero-initialized bytes, and its constructor has not run. After the first successful pass, later calls skip the declaration's initializer entirely. That is why `static Config instance;` inside `Config& config()` builds exactly one `Config`, on demand, which is the basis of the **construct-on-first-use** idiom, often called a Meyers singleton. ## What the standard guarantees The rule in the declaration-statement clause has five parts worth naming in an interview: 1. **Once.** The variable is considered initialized when its initializer completes, and is never initialized again. 2. **Concurrent callers wait.** "If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization." This has been the rule since C++11; before that, two threads could both run the constructor. 3. **Exceptions retry.** If the initializer exits by throwing, initialization is not complete, so it is tried again the next time control enters the declaration. The code example shows the constructor running twice. 4. **No implementation deadlock.** A conforming implementation cannot introduce a deadlock around the initializer; deadlocks from the program's own logic are still possible. 5. **Recursion is undefined.** If control re-enters the same declaration recursively while it is still being initialized, the behaviour is undefined. Contrast point 3 with a **namespace-scope** variable: if its dynamic initialization throws, `std::terminate` is called, because there is no "next time". ## How compilers implement it The standard says nothing about mechanism; implementations agree on the outline. Each such variable gets a hidden **guard** recording whether initialization finished. Every call performs a cheap check of the guard; only when it is clear does the code take a slow path. On platforms that follow the Itanium C++ ABI, which GCC and Clang use on Linux and macOS, that slow path calls `__cxa_guard_acquire`, runs the initializer, then calls `__cxa_guard_release`, or `__cxa_guard_abort` if the initializer throws. Compiling the example with `-O2 -S` on Apple clang 21 shows all three calls. For a type with a non-trivial destructor, the generated code also registers that destructor (through `__cxa_atexit` on these platforms) so it runs during `std::exit`, in reverse order of construction relative to other statics. ## Costs and pitfalls - **Fast-path cost.** After initialization each call still pays a guard check and a branch. In a hot loop, hoist the returned reference into a local. - **Opting out.** GCC documents `-fno-threadsafe-statics` as dropping the code that uses the C++ ABI's thread-safe initialization routines, to save a little code size. Clang accepts the same flag. Use it only where no second thread can ever reach the declaration. - **Logic deadlocks.** If the initializer locks a mutex that another thread holds while that thread calls the same function, both wait forever. The guarantee in point 4 covers the implementation's own locking, not yours. - **Exit-time use.** A function-local static is destroyed at exit like any static object, so a destructor of another static that calls the function later can touch a dead object. - **Not per thread.** The object is shared by every thread; making it `thread_local` instead gives one lazily built object per thread. ## When to reach for it Use a function-local static when a program-wide object must exist before its first user, whatever order the translation units initialize in, and when lazy construction is acceptable. Prefer `constinit` or `constexpr` when the value can be computed at compile time, because then there is no guard, no first-call cost and nothing to order. Two neighbouring tools are often confused with it. `std::call_once` with a `std::once_flag` gives the same once-only guarantee for code that is not a variable initializer, such as wiring up callbacks. A `thread_local` block variable is also initialized on the first pass through its declaration, but once **per thread**, so it needs no cross-thread waiting at all. Interviewers like to hear that the language feature was designed so that the common case, one shared lazily built object, needs neither.

  • What does a function-local static cost on every call after the first?
    The standard leaves that to the implementation. GCC and Clang emit a check of a hidden guard on every call and branch to the locking slow path only while it is clear, so the steady-state cost is a load and a branch. That is small but not free in a hot loop, where binding the returned reference to a local once is the usual fix. A constant-initialized static has no guard at all.
  • Can initializing a function-local static deadlock?
    The implementation may not add a deadlock of its own, but the program can create one. If thread A holds a `std::mutex` and calls the function while thread B is inside the static's initializer waiting for that same mutex, A waits for B's initialization and B waits for A's lock. Re-entering the same declaration recursively is a separate case: undefined behaviour, not a guaranteed deadlock.
  • How does this differ from a throwing initializer of a namespace-scope global?
    For a function-local static, a throwing initializer leaves it uninitialized and the next pass retries. For a non-block variable with static or thread storage duration, an exception escaping its initialization calls `std::terminate`, because nothing would ever retry it. That is one reason to wrap risky global setup in a function-local static or an explicit init call from `main`.

It is like the first person to arrive unlocking a shared office: everyone who arrives meanwhile waits at the door, nobody unlocks it twice, and if the key jams the next arrival tries again.

  • A function-local static needs a std::call_once around it to be thread-safe in C++11 and later.
  • Function-local statics are constructed before main, just like globals.
  • If a function-local static's constructor throws, the program always terminates.
  • After the first call, a function-local static with a runtime initializer costs nothing to reach.
  • Re-entering a static's initializer recursively just returns the half-built object.