Hard
A volatile flag between two threads
producer() writes data then sets flag; consumer() spins on flag before (implicitly) reading data. flag is declared volatile bool. Is this program correct C++, and is volatile doing what the programmer probably intended?
main.cpp
#include <thread>
volatile bool flag = false;
int data = 0;
void producer() {
data = 42;
flag = true;
}
void consumer() {
while (!flag) {
// spin until flag is set
}
// ... use data here, expecting to see 42
}
int main() {
std::thread p(producer);
std::thread c(consumer);
p.join();
c.join();
}72 of 117 in C++