Search code examples
c++multithreadingstatic-variablesthread-local

Nested thread_local variable


When declaring static thread_local variable, then each thread has a copy of that variable. Imagine a thread then spins another thread, will this variable still be a copy in the nested thread?


Solution

  • A thread_local variable has an instance in every thread. It doesn't matter how the thread is created.

    Each instance of the thread_local variable is initialized per its initializing declaration. There are no copies being made from one instance to the other.

    The static keyword has a meaning completely orthogonal to thread_local. At block scope and class scope it is always redundant with thread_local. At namespace scope it gives the variable internal linkage, which means that every translation unit (.cpp file) will have its own instance of the variable as well, in addition to there being one instance per thread.