1

这是一个后续行动这是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;
}
4

1 回答 1

7

该标准描述了内存模型,特别是“数据竞争”的概念(第 1.10 节)。很明显,您的代码对变量存在数据竞争notify,因此存在未定义的行为。

要解决此问题,要么保护对notify锁的访问,要么将其设置为原子变量,例如std::atomic<int>.

于 2012-10-14T02:43:27.087 回答