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;
}
Nima Ghorab
  • 309
  • 1
  • 3
  • 13
  • in your case seems there's no difference – fas Sep 23 '19 at 09:32
  • 1
    This question has an answer https://stackoverflow.com/questions/11983875/what-does-the-thread-local-mean-in-c11 – Fryz Sep 23 '19 at 09: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. – Nima Ghorab Sep 23 '19 at 09: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: https://wandbox.org/permlink/ZbWGoWOiEDsXkUCE. – Daniel Langr Sep 23 '19 at 09:39

1 Answers1

3

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_static. 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 !

Ajay
  • 18,086
  • 12
  • 59
  • 105
  • 1
    Hi, just to clarify, do you mean `thread_local` instead of `thread_static` at the latter part of your answer? – haxpor Oct 15 '20 at 14:44