1

これは、 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;
}
4

1 に答える 1

7

この規格は、メモリモデル、特に「データ競合」の概念について説明しています(セクション1.10)。notifyコードに変数のデータ競合があり、したがって未定義の動作があることはかなり明白です。

この問題を解決するには、アクセスをロックで保護するか、。notifyなどのアトミック変数にしますstd::atomic<int>

于 2012-10-14T02:43:27.087 に答える