C++ thread_local Keyword
Example
Create a thread_local variable and change it in a function:
thread_local int myNum = 0;
void addFive() {
myNum += 5;
}
int main() {
addFive();
addFive();
cout << myNum;
return 0;
}
Definition and Usage
The thread_local keyword specifies that each thread has its own copy of a variable.
A thread is a part of a program that can run at the same time as other parts. For example, a game can use one thread to play music, and another thread to draw the screen.
A normal global variable is shared by all threads. A thread_local variable is not shared: each thread gets its own copy, which starts with the same value. In a program with only one thread, like the example above, it works like a normal global variable.
Related Pages
Read more about global variables in our C++ Scope Tutorial.