- 1 year ago
Is it possible to create thread private variables?
In most programming languages, including C++, you can create thread-private variables using thread-local storage (TLS) mechanisms provided by the language or runtime.
In C++, you can use the thread_local
keyword to declare variables that are specific to each thread. Here's an example:
cpp#include <iostream>
#include <thread>
thread_local int threadSpecificVariable;
void threadFunction() {
threadSpecificVariable = 42;
std::cout << "Thread-specific variable value: " << threadSpecificVariable << std::endl;
}
int main() {
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
return 0;
}
In this example, the threadSpecificVariable
is declared as thread_local
, which means each thread will have its own separate copy of the variable. When you run the program, each thread will set its own value for threadSpecificVariable
, and accessing it within the thread will give you the thread-specific value.
It's important to note that thread-local storage is specific to each thread and is not shared across threads. Each thread has its own instance of the variable.