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.
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.
来源:https://stackoverflow.com/questions/35508133/when-exactly-is-a-thread-local-variable-declared-at-global-scope-initialized