Thread-Local Data

Contents[Show]

By using the keyword thread_local, you define the thread local data. Thread-local can easily be explained in a few words.

thread_local

When needed, thread local data will be created for each thread. thread-local data exclusively belongs to the thread and behaves like static data. That means, it will be created at its first usage and its lifetime is bound to the lifetime of the thread. Often thread local data is called thread local storage.

Dealing with thread local data is straightforward.

 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
32
33
34
35
36
37
// 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::cout
  std::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 thread_local in line 8, the thread-local string s is created. The threads t1 - t4 (line 27 - 30) use the function addThreadLocal (line 12 - 21) as their work package. The threads get as argument the strings "t1" to "t4" respectively and add them to the tread-local string s. In addition, addThreadLocal displays the address of the string s in line 18.
 

threadLocal

The output of the program shows it implicitly in line 17 and explicitly by the address in line 18. The tread-local string is created for each string s. First, each output shows a new tread-local string, second, each string s has a different address.

What's next?

Condition variables are easy to use wrong. Why? Have a look at the next post. (Proofreader Arne Mertz)

 

 

 

 

 

 

title page smalltitle page small Go to Leanpub/cpplibrary "What every professional C++ programmer should know about the C++ standard library".   Get your e-book. Support my blog.

 

Add comment


My Newest E-Book

Latest comments

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 90

All 333381

Currently are 147 guests and no members online