Reputation: 6026
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?
Upvotes: 2
Views: 1151
Reputation: 19965
I compiled
int regular_global_int;
__thread int static_thread_local_int;
int main()
{
regular_global_int = 1;
static_thread_local_int = 1;
}
at http://ellcc.org/blog/?page_id=340 I had to take off the static to keep the optimizer from getting rid of the static variable. I got
main: # @main
# BB#0: # %entry
movl $1, regular_global_int(%rip)
movl $1, %fs:static_thread_local_int@TPOFF
xorl %eax, %eax
retq
for the x86_64. The thread local variable is accessed differently to provide the thread local storage.
Upvotes: 1
Reputation: 119382
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.
Upvotes: 3