1

Can someone clearly and simply explain what is the difference between i and j variables?

#include <thread> using namespace std; void f(int n) { thread_local int i = n; int j = n; } int main() { thread t1(f, 1); thread t2(f, 2); t1.join(); t2.join(); return 0; } 
4
  • in your case seems there's no difference Commented Sep 23, 2019 at 9:32
  • 1
    This question has an answer stackoverflow.com/questions/11983875/… Commented Sep 23, 2019 at 9:33
  • 1
    I didn't fined anything about comparison of these two in C++! I need to know where I should use thread_local and where I should only use local variable in function which passes to a thread. Commented Sep 23, 2019 at 9:34
  • To see the difference, add std::cout << i++ << " " << j++ << std::endl; into your f function and run a (single) thread as follows: thread t([]{ f(1); f(1); f(1); });. Live demo: wandbox.org/permlink/ZbWGoWOiEDsXkUCE. Commented Sep 23, 2019 at 9:39

1 Answer 1

6

thread_local implies static when static is omitted.

A local static variable preserves its value when a given function is called multiple times. You may read about static variable elsewhere.

Now, I assume you do know what static variable is - the important things are just:

  • static variables have local scope
  • (but) static variables have global existence

The second point makes a static variable's memory accessible to other functions by C++ references and pointers - it proves that the static variable has just one copy - across all threads of the process. You need to know what threads are and how to create/program threads.

Now, to the question. You know that Global variables have global scope and global accessibility, but when you run two or more instances of your program, both/all of them would have a SEPARATE copy of that global variable. That means each process would have a separate copy of that global variable.

So, what if you wanted to have a SEPARATE copy of static variable per thread? You use thread_local. Each thread will have a separate copy of that static variable.

Interestingly, you can apply thread_local to global variables also - thence each thread will receive a separate copy of those global variables also!

// Globals int counter; thread_local int this_thread_counter; // Each thread will have separate copy 

Now, think how strtok would work - think about the (concurrent) calls to strtok !

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.