![]() |
VOOZH | about |
Thread local storage (TLS) is a feature introduced in C++ 11 that allows each thread in a multi-threaded program to have its own separate instance of a variable. In simple words, we can say that each thread can have its own independent instance of a variable. Each thread can access and modify its own copy of the variable without interfering with other threads.
thread_local int my_variable;
Example 1:
Output
Thread 140093779908160 counter = 1 Thread 140093788300864 counter = 1
Example 2:
Output
Hello from thread 139683844367936 Hello from thread 139683852760640
It allows each thread to have its own separate instance of a static variable. Similar to TLS, each thread can access and modify its own copy of the static variable without affecting other threads but with static storage duration, which means the variable persists across multiple invocations of the function within the same thread.
Example:
Output
Thread ID: 140702226085440, Variable: 1 Thread ID: 140702234478144, Variable: 1
Thread local storage (TLS) in C++ allows each thread to have its own separate instance of a variable. TLS variables have their own lifetime, visibility, and scope within each thread. TLS can be used to maintain thread-specific data without interfering with other threads.