我有以下一些使用线程和静态变量初始化的C ++ 11代码。我的问题是:
C ++语言对静态变量的单个初始化做出了什么保证或保证 - 下面的代码显示了正确的值,但我似乎无法在新标准中找到提及内存模型应该如何交互的段落有线程。如果变量变为线程本地?
#include <iostream>
#include <thread>
class theclass
{
public:
theclass(const int& n)
:n_(n)
{ printf("aclass(const int& n){}\n"); }
int n() const { return n_; }
private:
int n_;
};
int operator+(const theclass& c, int n)
{
return c.n() + n;
}
void foo()
{
static theclass x = 1;
static theclass y = x + 1;
printf("%d %d\n",x.n(),y.n());
}
int main()
{
std::thread t1(&foo);
std::thread t2(&foo);
t1.join();
t2.join();
return 0;
}
答案 0 :(得分:8)
代码将按照您的期望进行。见§6.7.4
静态局部变量是:
...初始化控件首次通过其声明... 如果控件在变量的同时输入声明 在初始化时,并发执行应等待完成 初始化。
换句话说,编译器确保您的线程在静态本地的初始化上合作。它们将被初始化一次,每个线程只有在完全初始化后才能访问该对象。
编译器只会在使用thread_local
关键字明确请求时创建线程局部变量。