Reputation: 17487
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?
Upvotes: 3
Views: 2759
Reputation: 69
When called repeatedly, the population of a newly constructed vector requires brand new allocations with new. This can end up degrading the performance on functions that are called repeatedly. If the vector is static, the same allocation can be re-used with just a clear. (A call to new() is avoided) However, this makes it thread-unsafe, hence the thread_local.
Upvotes: -1
Reputation: 241911
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.
Upvotes: 5