C Reference ยท Keywords and Statements
The thread_local specifier
Reference for C thread_local (_Thread_local): per-thread copies of variables, linkage rules, initialization and use with threads.h or pthreads.
A variable declared thread_local has thread storage duration: every thread gets its own separate copy, created when the thread starts and destroyed when it ends. Changes in one thread are invisible to others, so no lock is needed to protect it.
It is a keyword in C23. In C11 and C17 the keyword is _Thread_local, and <threads.h> defines the macro thread_local. Typical uses are per-thread error codes (like errno), scratch buffers, and caches that would otherwise need a mutex.
thread_local int counter = 0;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
thread_local type name = constant-initializer; static thread_local type name; extern thread_local type name;
| Part | Description |
|---|---|
thread_local |
Storage-class specifier (C23 keyword; _Thread_local before). |
| initializer | Must be a constant expression (C11/C17/C23): no run-time initialization like = f(). |
Returns: nothing; it is a declaration.
Errors: it cannot be applied to function declarations or to block-scope variables without static or extern (a plain local is already per-call). A declaration of the same name must use thread_local consistently in every file.
Usage notes
- Without
static/extern, a file-scopethread_localobject has external linkage;static thread_localkeeps it private to the file. - Initialization happens once for every new thread, with the same constant initial value. Use
or constants only. - Cost. Access is usually a little slower than a normal global (the address is found through a thread pointer). Do not use it for tiny hot paths unless needed.
- Lifetime. Pointers to a thread-local object must not outlive the thread; no other thread should keep one.
- Not inherited. A new thread starts with the initial value, not the creating thread's value.
- Works with POSIX threads too. GCC supports
thread_localobjects inpthreadthreads;<threads.h>needs glibc 2.28 or later. - Resources. The language has no destructor for thread-local objects; free resources at the end of the thread function.
- Do not combine with
registerorauto;static,externandconstexprare allowed (C23).
Related
<threads.h>,pthread,static,errno- Lessons: Threads, Storage classes