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?
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.