Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++11 allow you to declare a local variable as thread_local? [duplicate]

int main()
{
    thread_local int n;
}

The code above is legal in C++11.

According to cppreference:

The thread_local keyword is only allowed for objects declared at namespace scope, objects declared at block scope, and static data members.

I just wonder:

A local variable is always on the current thread's stack, so it's always thread-local. thread_local int n; is completely identical to int n; in such contexts.

Why does C++11 allow to declare a local variable as thread_local, rather than explicitly disable it to avoid abuse?

like image 284
xmllmx Avatar asked Feb 09 '17 07:02

xmllmx


1 Answers

According to the standard, a thread_local variable at block scope is also implicitly static. However, not all static variables are thread_local.

So

 int main()
 {
       thread_local int x;
 }

is actually equivalent to

 int main()
 {
       thread_local static int x;
 }

but different from;

 int main()
 {
       int x;    //  auto implied
 }
like image 88
Peter Avatar answered Nov 14 '22 21:11

Peter