_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.

CategoryC11 features
KindKeyword / Statement
C standardC11

📝 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏