【问题标题】:When exactly is a thread_local variable declared at global scope initialized?在全局范围内声明的 thread_local 变量究竟是什么时候初始化的?
【发布时间】:2016-02-19 14:52:19
【问题描述】:

例如:

#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 中仍然不完全清楚 n 何时初始化。

【问题讨论】:

  • 线程初始化时。
  • 对于每个线程(线程)被初始化时。
  • 看起来确实有点混乱。 local 是每个线程的 n 的 storage。但是 n 的范围(即它在代码中的可见性)是全局的。
  • 初始化本身发生在答案(此处和链接的问题中)描述:在使用之前。具体什么时候?标准未指定。

标签: c++ multithreading initialization storage


【解决方案1】:

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

准确的说是要初始化3次。

【讨论】:

    猜你喜欢
    • 2014-08-06
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多