_Thread_local C11 thread-local storage
_Thread_local C11 thread-local storage
C11's _Thread_local creates an initialized, thread-lifetime copy per thread. It combines with static or extern and cannot replace atomics for shared data.
| Category | C11 features |
|---|---|
| Kind | Keyword / Statement |
| C standard | C11 |
📝 Syntax
_Thread_local int tls_var = 0;
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
main thread: first = 1, second = 2
main thread copy = 2
ℹ️ Info The example runs only the main thread, avoiding dependencies on pthread or threads.h link options, and reliably prints 1 and 2 from the main thread's copy. A newly created thread starts from its own initial calls value rather than sharing the main thread's copy.
🏷️ Related C11 features
📚 Related Tutorials
❓ FAQ
QIs a _Thread_local variable shared by multiple threads?
AThreads do not share the same object; each has its own copy, address, and lifetime. A modification in one thread does not affect another's copy. If one copy's address is passed to another thread, access still requires attention to lifetime and synchronization.
QWhat does static _Thread_local mean when used together?
Astatic specifies internal linkage, making the name visible only in the current translation unit. _Thread_local specifies thread storage duration, giving each thread an independent copy. The two describe different properties.
QWhy doesn't the thread-local example create a new thread?
AThe main thread already has a thread-local copy, sufficient to show that it retains its value across calls without a thread library or extra link options. Real multithreaded programs should still create threads for the target platform and verify copy isolation.