Davit Tevanian
Davit Tevanian

Reputation: 861

When exactly is a thread_local variable declared at global scope initialized?

For example:

#include <thread>

thread_local int n = 1;

void f()
{
    ++n; // is n initialized here for each thread or prior to entering f()?
}

int main()
{
    std::thread ta(f);
    std::thread tb(f);

    ta.join();
    tb.join();
}

It's still not entirely clear from here when is n initialized.

Upvotes: 6

Views: 607

Answers (1)

SergeyA
SergeyA

Reputation: 62613

Simple enough, and all according to specification. n is going to be initialized whenever the new thread is run - before you enter any thread-specific functions.

To be exact, it is going to be initialized three times.

Upvotes: 6

Related Questions