User Tools

Site Tools


c:c_threads:thread_local_storage_thread_local

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;
}

returns:

Value of globalVar in thread 140620033623808 is 5
Value of globalVar in thread 140620025231104 is 20
Value of globalVar in MAIN thread is 1

If globalVar was not declared thread_local then the returned result would be:

Value of globalVar in thread 140275965699840 is 20
Value of globalVar in thread 140275957307136 is 20
Value of globalVar in MAIN thread is 20

NOTE: If the global value was not thread local, the change made by each thread will be persisted outside the thread.

c/c_threads/thread_local_storage_thread_local.txt · Last modified: 2021/03/05 16:10 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki