【发布时间】:2011-10-17 05:56:07
【问题描述】:
我有以下使用线程和静态变量初始化的 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;
}
【问题讨论】:
标签: multithreading initialization c++11 static-members memory-model