Search code examples
c++multithreadinglocal-variablesthread-local

thread_local vs local variable in C++


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

Solution

  • 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 !