skip to content

In a C++ worker thread, what does a thread_local variable give each thread, and when is it constructed and destroyed?

level: middleimportance: should knowfreq 45%

answer

  1. one object per thread
  2. same name, different storage
  3. block scope implies static
  4. built on first pass, per thread
  5. destroyed when the thread ends

basics

~20 s

A thread_local variable has a distinct object in every thread that uses it. A block-scope one is initialized the first time each thread passes its declaration, and each thread's constructed objects are destroyed when that thread's initial function returns.

solid answer

~40 s

`thread_local` gives a variable **thread storage duration**: there is a distinct object per thread, and the name always refers to the current thread's object. At block scope `static` is implied, and dynamic initialization happens the first time each thread passes the declaration. For a namespace-scope `thread_local`, it is implementation-defined whether initialization runs before the thread's first statement or is deferred to that thread's first odr-use of a `thread_local` from the same translation unit. Each thread's constructed objects are destroyed when its initial function returns or it calls `std::exit`, and that destruction strongly happens before any static object is destroyed. Typical use: a per-worker scratch buffer or counter with no locking. Pitfalls: a pointer to another thread's `thread_local` dangles once that thread exits, and a reused worker keeps its values between tasks.

code

cpp · 28 lines
cpp
#include <cstdio>
#include <thread>
#include <vector>

struct ScratchBuffer {
    std::vector<unsigned char> bytes;
    ScratchBuffer() { bytes.reserve(1 << 20); std::puts("scratch built"); }
    ~ScratchBuffer() { std::puts("scratch freed at thread exit"); }
};

int encode_frames(int count) {
    thread_local ScratchBuffer scratch;   // block scope: static is implied
    thread_local int frames = 0;          // a separate counter in every thread
    frames += count;
    return frames;
}

int main() {
    auto worker = [](int segment) {
        encode_frames(100);
        std::printf("segment %d: this thread's total %d\n", segment, encode_frames(segment));
    };
    std::thread a(worker, 1);
    a.join();
    std::thread b(worker, 2);
    b.join();
    std::printf("main thread total %d\n", encode_frames(0));
}

go deeper

for a junior

Recall that thread_local gives every thread its own copy of the variable, with no locking needed.

for a middle

Explain when each thread's object is initialized at block and namespace scope and when it is destroyed.

for a senior

Spot the escaping pointer, the reused-thread state leak and the exit-time destructor that never runs for a detached thread.

for a principal

Decide where per-thread caches are acceptable in a codebase and how their state is reset or merged.

## What thread_local means `thread_local` is a storage-class specifier. A variable declared with it has **thread storage duration**: the storage lasts as long as the thread that created it, and the standard says there is **a distinct object per thread**, with every use of the name referring to the current thread's object. Two threads running the same function therefore see two different variables behind one name, and need no lock to use them. Where it can appear: - on a variable at **namespace scope**; - on a variable at **block scope**, where `static` is implied when no other storage-class specifier is written; - on a **static data member**; - on a structured binding declaration. It cannot be applied to a non-static data member or a function parameter: an object's members live wherever the object lives. ## When each thread's object is built | Declared at | Dynamic initialization | |---|---| | block scope | the first time **that thread** passes the declaration; a throwing initializer is retried next time | | namespace scope | implementation-defined: before the thread's first statement, or deferred until that thread first odr-uses a `thread_local` defined in the same translation unit | Constant initialization and zero-initialization happen before any of this, so a `thread_local int frames = 0;` needs no run-time initializer. In the transcoder example below, each segment worker gets its own one-megabyte `ScratchBuffer` and its own frame counter, built lazily on first use. ## When it is destroyed The standard destroys a thread's constructed `thread_local` objects as a result of the thread **returning from its initial function**, or of that thread calling `std::exit`. For the main thread, returning from `main` calls `std::exit`, so its `thread_local` objects are destroyed there too. Two ordering guarantees matter: 1. All of a thread's `thread_local` destructions **strongly happen before** the destruction of any object with static storage duration, so a `thread_local` destructor may still use a global. 2. Objects never constructed in a thread are never destroyed in it; a thread that did not touch the scratch buffer pays nothing. ## Where it bites - **Escaping pointers.** Handing `&scratch` to another thread is fine while the owner runs; once the owner exits, the pointer dangles and using it is undefined behaviour. - **Reused worker threads.** A thread that runs many tasks, such as a pool worker, keeps its `thread_local` values between tasks. Code that assumed a fresh counter per task gets a running total. Reset at task start, or keep task state in the task. - **Detached threads at exit.** A detached thread still running when the process ends may never run its `thread_local` destructors, so do not rely on them to flush output. - **Cost of access.** Reading a `thread_local` is usually cheap, but the code the compiler emits depends on the platform's thread-local storage model, and it can be slower than a plain global, especially across shared libraries. - **Initialization order within a thread** for namespace-scope variables is as fragile as the static initialization order problem; prefer block-scope `thread_local` behind a function. ## thread_local beside the alternatives | Declaration | Objects | Lifetime | |---|---|---| | `int n;` inside a function | one per call | until the call returns | | `static int n;` inside a function | one per program | until static destruction at exit | | `thread_local int n;` inside a function | one per thread that reaches it | until that thread ends | | member of a worker object | one per object | the object's lifetime | The last row is often the better design: state owned by an explicit worker object is visible in its type, testable without threads, and reset by constructing a new object. ## When to reach for it Use `thread_local` for **per-thread caches and scratch space** that would otherwise need a lock: encoding buffers, random-number engines, per-thread statistics merged at the end, an error-context string. Do not use it to pass data **between** threads, and do not use it for state that belongs to a unit of work rather than to the thread that happens to run it.

  • Can a thread_local object's destructor safely use a global object?
    Yes, as far as ordering goes. The standard says the destruction of all of a thread's `thread_local` objects strongly happens before the destruction of any object with static storage duration, so the global is still alive. The reverse is not true: a static object's destructor must not use a `thread_local`, which may already be gone.
  • Why can a thread_local counter give wrong per-task numbers in a worker that runs many tasks?
    The variable belongs to the thread, not the task. A reused thread keeps the value from its previous task, so a counter meant to start at zero for each task accumulates. Reset it explicitly when a task starts, or store task state in the task object.
  • Can you declare a non-static data member thread_local?
    No. The specifier applies only to variables at namespace or block scope, structured bindings and static data members; a non-static member is part of an object whose storage is decided by the object, so the declaration is ill-formed.

  • A thread_local variable is shared by all threads but protected by a lock.
  • A block-scope thread_local is constructed once, by the first thread that reaches it.
  • thread_local objects are destroyed when the program exits, not when their thread ends.
  • A pointer to another thread's thread_local stays valid after that thread exits.
  • A thread_local value is reset automatically before each task a worker runs.