Search code examples
c++multithreadinggccthread-local

Non-static global variable vs. global static __thread variable


If I define a static __thread variable in global scope, is it equivalent to the regular non-static global variable? In other words, are the following two variables equivalent to each other if they are all in global scope:

int regular_global_int;
static __thread int static_thread_local_int;

If the answer is no, can I know what's the major different between these two and when should I use which one?


Solution

  • Global variables, and more generally namespace-scope variables, automatically have static storage duration when not declared with a storage class specifier. At namespace scope, static does not mean "static storage duration"; it means the variable has internal linkage. Hence

    int x;
    static int x;
    

    at namespace scope both declare x with static storage duration but the two declarations are nevertheless not the same as the first declaration gives x external linkage but the second gives it internal linkage.

    In the case that you write

    static thread_local int x;
    

    the thread_local storage class specifier causes x to have thread-local storage duration (rather than static storage duration) whereas static itself again has its usual meaning at namespace scope. So x is thread-local and it has internal linkage.