c++ - `thread_local` 全局变量什么时候初始化?

标签 c++ multithreading c++11 thread-local

考虑以下示例(为简单起见,省略了 cout 上的锁守卫)。

#include <future>
#include <iostream>
#include <thread>

using namespace std;

struct C
{
  C() { cout << "C constructor\n";}
  ~C() { cout << "C destructor\n";}
};

thread_local C foo;

int main()
{
   int select;
   cin >> select;
   future<void> f[10];
   for ( int i = 0;i < 10; ++i)
       f[i] = async( launch::async,[&](){ if (select) foo; } );
   return 0;
}

在 clang 和 gcc 上,如果用户写入 '0',则该程序不输出任何内容,而如果用户输入非零,它会打印 Constructor/Destructor 10 次数字。 此外,clang 提示明显未使用的表达式结果。

由于 thread_local 存储生命周期应该跨越整个线程的生命周期,我希望 foo 变量在每个线程中都被初始化,而不管用户输入如何。

我可能想要一个 thread-local 变量,其唯一目的是在构造函数中产生副作用,标准是否要求 thread_local 对象是首次使用时初始化?

最佳答案

标准允许这种行为,尽管它不能保证。从 3.7.2/2 [basic.stc.thread]:

A variable with thread storage duration shall be initialized before its first odr-use (3.2) and, if constructed, shall be destroyed on thread exit.

对象也有可能是在其他时间构造的(例如在程序启动时),因为“首次使用之前”的意思是“在任何时候只要它在之前”而不是“就在之前”。

关于c++ - `thread_local` 全局变量什么时候初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24253584/

相关文章:

java - 如何等待所有线程完成

c++11 - 为什么 C++ 标准不禁止这种可怕的用法?

c++ - 返回对 C++ 中可能更改的数据的引用

java - 对生产者消费者解决方案感到困惑(同步说明)

c# - 如何从 .Net 中的超线程中获得最大 yield

c++11 - 什么样的迭代器支持随机访问但不支持 C++ 中的连续存储?

c++ - 当 malloc()-ing 相同的结构时,如何在结构中使用 C++ 字符串?

c++ - 我无法读取空格并使用 devc++ 在 c++ 中输入

c++ - 编译器是否被迫拒绝无效的 constexpr?

c++ - vector 迭代器不可取消引用。成对的优先队列。