【发布时间】:2014-08-06 20:41:26
【问题描述】:
考虑以下示例(为简单起见,省略了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 对象在第一次使用时被初始化?
【问题讨论】:
标签: c++ multithreading c++11 thread-local