Reputation: 36451
This is a follow-up to Volatile in C++11
In the question, I was told that the following code is exhibiting undefined behavior in C++11, which confused me greatly. Is there any material that I can read (sections of the standard perhaps) concerning the behavior of volatile in C++11?
Or can someone please explain where the problem lies?
#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;
}
Upvotes: 1
Views: 190
Reputation: 477512
The standard describes the memory model, and in particular the notion of a "data race" (Section 1.10). It is fairly obvious that your code has a data race for the variable notify
, and thus undefined behaviour.
To fix the problem, either guard access to notify
by a lock, or make it an atomic variable such as an std::atomic<int>
.
Upvotes: 7