Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit of using static for thread_local variable?

According to this comment, I can see the definition

void f() {
    thread_local vector<int> V;
    V.clear();
    ... // use V as a temporary variable
}

is equivalent to

void f() {
    static thread_local vector<int> V;
    V.clear();
    ... // use V as a temporary variable
}

But I have found the following like code is used in some Open Source projects:

void f() {
    static thread_local vector<int> V;
    ......   
}

Per my understanding, it should be meaningless to add static here. So is there any benefit of using static for thread_local variables? Such as do some compiling optimizations?

like image 921
Nan Xiao Avatar asked Oct 21 '25 05:10

Nan Xiao


1 Answers

The answer you cite is about C++, and in C++ it appears that the two declarations are identical. But that's not true in C, and since your question is tagged with both C and C++ tags, it is not clear which language you care about.

In C, if you declare a thread-local variable inside a function, you must declare it either static or extern (depending on which linkage it has). See §6.7.1, paragraph 3:

In the declaration of an object with block scope, if the declaration specifiers include _Thread_local, they shall also include either static or extern. If _Thread_local appears in any declaration of an object, it shall be present in every declaration of that object.

So that's an advantage of declaring a variable static thread_local: it allows C compilation, provided you include the threads.h library header.

However, it does not affect performance in any way in either language.

like image 102
rici Avatar answered Oct 25 '25 11:10

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!