什么时候在全局范围内声明的thread_local变量是否已初始化?

时间:2016-02-19 14:52:20

标签: c++ multithreading initialization storage

例如:

#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();
}

初始化时,here仍然不完全清楚。

1 个答案:

答案 0 :(得分:4)

足够简单,并且都符合规范。每当新线程运行时,都会初始化n - 在您输入任何特定于线程的函数之前。

确切地说,它将被初始化三次。