考虑以下示例(为简单起见,省略了 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/