How to store thread-specific data in c++ globally?

Member

by anissa , in category: General Help , 2 months ago

How to store thread-specific data in c++ globally?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by coty_beier , 2 months ago

@anissa 

In C++, you can use the thread_local keyword to declare thread-specific variables. Thread-local variables have their own separate storage for each thread, and their values are not shared between threads. Below is an example of how to store thread-specific data globally:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <thread>

// Global thread-local variable
thread_local int g_data;

// Function to print the thread-specific data
void printData() {
    std::cout << "Thread " << std::this_thread::get_id() << ": " << g_data << std::endl;
}

// Thread function
void threadFunction() {
    // Set thread-specific data
    g_data = std::this_thread::get_id();
  
    // Print thread-specific data
    printData();
}

int main() {
    // Create multiple threads
    std::thread t1(threadFunction);
    std::thread t2(threadFunction);
  
    // Wait for the threads to finish
    t1.join();
    t2.join();
  
    return 0;
}


In this example, the g_data variable is declared as thread_local, which means that each thread will have its own separate copy of the variable. The threadFunction sets the thread-specific data by assigning the current thread's ID to g_data and then calls the printData function to print the stored data.


When you run the example, you will see that each thread prints its own ID, which confirms that each thread has its own separate copy of g_data.


Note that the thread_local keyword is only available in C++11 and later versions. If you are working with an earlier version of C++, you may need to use platform-specific APIs or libraries to achieve the same functionality.