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?
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. Henceat namespace scope both declare
x
with static storage duration but the two declarations are nevertheless not the same as the first declaration givesx
external linkage but the second gives it internal linkage.In the case that you write
the
thread_local
storage class specifier causesx
to have thread-local storage duration (rather than static storage duration) whereasstatic
itself again has its usual meaning at namespace scope. Sox
is thread-local and it has internal linkage.