Skip to main content
A thread-local variable in C is a variable with thread storage duration, meaning each thread in a multithreaded program receives its own independent, isolated instance of the variable. The memory for the variable is allocated when a thread is created and automatically deallocated when that specific thread terminates. Introduced in the C11 standard, thread-local variables are declared using the _Thread_local storage-class specifier. Including the <threads.h> standard library header provides the thread_local convenience macro, which expands to _Thread_local.

Technical Characteristics

Storage Duration and Scope Applying thread_local alters the storage duration of a variable to thread storage duration. It can be applied to variables at file scope (globals) or block scope (inside functions). According to the C11 standard (6.7.1), if _Thread_local is used on a block-scope declaration, it cannot be used alone; it must be explicitly accompanied by either the static or extern keyword. Linkage The linkage of a thread-local variable depends on its declaration context and accompanying specifiers:
  • External Linkage: File-scope declarations without the static keyword, or block-scope declarations with the extern keyword.
  • Internal Linkage: File-scope declarations combined with the static keyword.
  • No Linkage: Block-scope declarations combined with the static keyword.
Initialization Rules In C, thread-local variables must be initialized with a constant expression. Initialization occurs at thread startup (C11 Standard 6.2.4), before the thread executes any code. For the initial (main) thread, initialization occurs at program startup. Unlike C++, C does not perform lazy initialization upon the first evaluation of the variable. If no explicit initializer is provided, the variable is implicitly zero-initialized. Addressability and Pointers Applying the address-of operator (&) to a thread-local variable yields a pointer to the specific instance belonging to the calling thread. While it is syntactically valid to pass this pointer to another thread, doing so requires strict lifetime management; dereferencing the pointer after the owning thread has terminated results in undefined behavior.

Pre-C11 Compiler Extensions

For codebases predating C11 or operating on non-compliant compilers, thread-local storage is typically implemented via compiler-specific extensions rather than standard keywords:
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More