一个 thread_local 变量在全局作用域中什么时候被声明并初始化?

6

例如:

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

这里仍然不完全清楚n何时被初始化。


当线程被初始化时。 - Otávio Décio
对于每个线程,在其初始化时。 - Simon Kraemer
1
相关:https://dev59.com/YmAf5IYBdhLWcg3w0VUf - Revolver_Ocelot
看起来有点混乱。local 是每个线程中 n 的 _存储_。但是 n 的作用域(即其在代码中的 _可见性_)是全局的。 - Leo Heinsaar
初始化本身是在答案中所描述的那样进行的:在使用之前。具体时间?标准没有规定。 - Leo Heinsaar
1个回答

6

这很简单,也符合规范。每当新线程运行时,在进入任何特定于线程的函数之前,n都会被初始化。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接