Home > Net >  Are static variables automatically thread local?
Are static variables automatically thread local?

Time:03-04

Are local static variables automatically thread local, or are they shared between threads?

void f() {
    static int x; // <-- need explicit _Thread_local ?
}

CodePudding user response:

There was static for block-scope variables before the C language specification acknowledged threads or had any support for them, much less _Thread_local specifically. In that context, when not combined with _Thread_local, it specifies static storage duration, meaning that the variable comes into existence (as if) at the beginning of program execution and exists and maintains its last-stored value for the entire run of the program. An object with static storage duration is shared by all threads.

On the other hand, _Thread_local always specifies thread storage duration, which means that the object so declared exists and maintains its last-stored value for the entire lifetime of a thread, and that the declared identifier designates a different object in each thread. When an object is declared _Thread_local at block scope, it must also bear either the extern or static qualifier, which conveys its linkage -- external or none.

extern declarations of any kind at block scope are unusual, but they do occasionally serve a useful purpose. Most of the time, though, static _Thread_local is what you will want for thread-local, block-scope variables.

CodePudding user response:

static and _Thread_local specify two different things.

A variable declared as static has static storage duration and has full program lifetime. A variable declared _Thread_local has thread storage duration and an instance of it exists for each thread.

CodePudding user response:

They are shared value between threads. As you already mentioned by yourself, if you want to make have independently value for each of thread then declare it something line that _Thread_local static int x;

  • Related