4

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?

1
  • 1
    Makes for better readability? Commented May 23, 2017 at 2:10

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

vector<int> is a syntax error in C, so I have removed the C tag.
-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.