这是一个后续行动这是C++11
在问题中,有人告诉我以下代码在 C++11 中表现出未定义的行为,这让我非常困惑。关于 C++11 中 volatile 的行为,我是否可以阅读任何材料(也许是标准的部分)?
或者有人可以解释问题出在哪里吗?
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
volatile int notify;
void watcher()
{
this_thread::sleep_for(chrono::seconds(2));
notify = 1;
cout << "Notification sent." << endl;
}
int main()
{
thread(watcher).detach();
notify = 0;
while (!notify)
{
cout << "Waiting." << endl;
this_thread::sleep_for(chrono::seconds(1));
}
cout << "Notification received." << endl;
return 0;
}