5
我有以下的C++ 11代碼使用線程和靜態變量初始化。我的問題是:C++靜態變量初始化和線程
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;
}