When is the thread_local variable declared in the global scope exactly defined?

For instance:

#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 is still not entirely clear from here when n is initialized.

+4
source share
1 answer

Simple enough and everything is in accordance with the specification. nwill be initialized whenever a new thread starts - before you enter any thread-related functions.

To be precise, it will be initialized three times.

+3
source

Source: https://habr.com/ru/post/1629580/


All Articles