#include <iostream>
#include <thread>
int x = 0;
int y = 0;
void f()
{
std::cout <<"f called\n";
static int c = 0;
while(y == 0)
{
++c;
}
std::cout << "c=" << c << std::endl;
std::cout << "x=" << x << std::endl;
}
void g()
{
std::cout <<"g called\n";
x = 42;
y = 1;
}
int main()
{
std::thread t1(f);
std::thread t2(g);
t1.join();
t2.join();
return 0;
}
当从另一个线程设置标志 y 时,f 应该打印 'x=42'(好吧,它也打印 x=0,但这不是这里的问题)
在调试模式下运行时,它按预期工作:
f called
g called
c=80213
x=42
但在发布模式下,第二个线程似乎冻结并且程序永远不会结束:
f called
g called
有人可以解释为什么吗?
PS。该程序使用mignw g++ 4.8.0编译