考虑以下代码:
#include <iostream>
#include <thread>
using std::cout;
using std::thread;
thread_local int a;
void foo()
{
a = a + 1;
cout << a << "\n";
}
void bar()
{
cout << a << "\n";
}
void baz()
{
cout << "Something\n";
}
int main()
{
thread first(foo);
thread second(bar);
thread third(baz);
second.join();
first.join();
third.join();
cout << a;
}
由于 a
具有线程存储持续时间,我们至少有三个不同的对象,用 a 表示并用于 first
、second
和 主
线程。我们不在 third
中使用 a
。有没有零初始化的a
可以用在third中?我问这个问题是因为我在标准中找不到任何相关内容:
Non-local variables with thread storage duration are initialized as a consequence of thread execution.
是否定义了实现?
最佳答案
N3337, 3.7.2.2
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.
3.2.2 太长了,不能在这里复制它,但本质上,如果它没有出现在执行的代码中,它就不能被“使用”。所以它没有(必须)用某些东西初始化。
关于c++ - 线程局部全局作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24701438/