C++ 11中的易失性 - 后续行动

Let*_*_Be 1 c++ volatile c++11

这是C++ 11中Volatile的后续内容

在这个问题中,我被告知下面的代码在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;
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 7

该标准描述了存储器模型,特别是"数据竞争"的概念(第1.10节).很明显,您的代码具有变量的数据争用notify,因此未定义的行为.

要解决这个问题,要么notify通过锁保护访问,要么使其成为原子变量,例如std::atomic<int>.

  • @Let_Me_Be:嗯,你可以使用原子变量来构造一个锁定原语. (2认同)