CKTIS / C++
thread_local — a separate variable for each thread
The thread_local keyword gives a variable thread storage duration: each thread has its own instance, retained between function calls. It does not create one shared variable protected against concurrent access.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
thread_local T name = initializer;
static thread_local T name = initializer;
extern thread_local T name;thread_local gives a variable thread storage duration. Each thread has a distinct instance, and using the name refers to the current thread's instance. A local variable of this kind retains its value between function calls in the same thread; an ordinary automatic variable does not, whereas a local static variable without thread_local is shared by calls from different threads.
In C++23, the specifier can be used for namespace-scope variables, block-scope variables, and static class data members, but not function parameters or non-static data members. It can be combined with static or extern; this does not change its thread storage duration. Every declaration of the same variable must include thread_local.
Dynamic initialization of a local thread_local variable occurs the first time control passes through its declaration in that thread. Do not generalize this to the initialization rules for all namespace-scope variables. A constructed object is destroyed at normal exit of its thread, not when the function returns. Do not use a pointer or reference to it after its lifetime has ended.
thread_local is neither a lock nor an atomic operation. Sharing a pointer to a particular instance with another thread does not create a new copy or provide synchronization. In the example, each thread increments its own count; join() ensures that the worker finishes before its results are read, making the expected output deterministic.
This entry targets C++23. The supplied source site hosts an evolving working draft rather than a frozen C++23 publication. A compiler flag is not evidence of operation in a production runtime.
Examples
#include <iostream>
#include <thread>
int next() {
thread_local int count = 0;
return ++count;
}
int main() {
const int first = next();
const int second = next();
int workerFirst = 0;
int workerSecond = 0;
std::thread worker([&] {
workerFirst = next();
workerSecond = next();
});
worker.join();
std::cout << first << ' ' << second << '\n';
std::cout << workerFirst << ' ' << workerSecond << '\n';
std::cout << next() << '\n';
}
Result
1 2 1 2 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.