Thread Local Data
This lesson explains how data that is local to a thread is created
We'll cover the following...
Thread-local data, also known as thread-local storage, will be created for each thread separately. It behaves like static data because it’s bound for the lifetime of the thread and it will be created at its first usage. Also, thread-local data belongs exclusively to the thread.
Press + to interact
// threadLocal.cpp#include <iostream>#include <string>#include <mutex>#include <thread>std::mutex coutMutex;thread_local std::string s("hello from ");void addThreadLocal(std::string const& s2){s += s2;// protect std::coutstd::lock_guard<std::mutex> guard(coutMutex);std::cout << s << std::endl;std::cout << "&s: " << &s << std::endl;std::cout << std::endl;}int main(){std::cout << std::endl;std::thread t1(addThreadLocal,"t1");std::thread t2(addThreadLocal,"t2");std::thread t3(addThreadLocal,"t3");std::thread t4(addThreadLocal,"t4");t1.join();t2.join();t3.join();t4.join();}
By using the keyword ...