C _Thread_local Keyword
Example
Create a _Thread_local variable and add 1 to it two times:
_Thread_local int counter = 0;
int main() {
counter++;
counter++;
printf("%d", counter);
return 0;
}
Definition and Usage
The _Thread_local keyword gives each thread its own copy of a variable. A thread is a part of a program that runs at the same time as other parts.
Normally, all threads share the same global variables. With _Thread_local, each thread gets its own copy, so a change in one thread does not affect the other threads. In a program with only one thread, like the example, it works like a normal global variable.
Use it on global variables, or together with static on variables inside a function. If you include <threads.h>, you can write thread_local instead of _Thread_local.
Related Pages
The _Atomic keyword makes a variable safe to use from many threads at the same time.
Read more about how long variables last in our C Storage Classes Tutorial.