c:c_threads:thread_local_storage_thread_local
This is an old revision of the document!
C - C++ Threads - Thread local storage (thread_local)
A thread_local object comes into existence when a thread starts and is destroyed when the thread ends.
Each thread has its own instance of a thread-Local object.
Example
A global variable globalvar is defined as thread_local.
This will give each thread its own copy of globalVar and any modifications made to globalVar will only persist inside that particular thread.
In this example, each of the two threads are modifying globalVar – but they are not seeing a change made by the other thread, neither is the main thread.
#include <iostream> #include <string> #include <thread> #include <functional> #include <mutex> thread_local int globalVar = 0; std::mutex mu; void PrettyPrint(int valueToPrint) { std::lock_guard<std::mutex> lock(mu); std::cout << "Value of globalVar in thread " << std::this_thread::get_id() << " is " << globalVar << std::endl; } void thread_Local_Test_Func(int newVal) { globalVar = newVal; PrettyPrint(globalVar); } int main() { globalVar = 1; std::thread t1(thread_Local_Test_Func, 5); std::thread t2(thread_Local_Test_Func, 20); t1.join(); t2.join(); std::cout << "Value of globalVar in MAIN thread is " << globalVar << std::endl; return 0; }
c/c_threads/thread_local_storage_thread_local.1614960426.txt.gz · Last modified: 2021/03/05 16:07 by peter