Hard
A spin loop with no locks and no atomics
worker() spins on a plain (non-atomic, non-volatile) bool, incrementing a plain long long counter, until main sets stop = true from a different thread with no synchronization at all. Compiled with optimizations (-O2), does the worker thread reliably observe the update and terminate its loop?
main.cpp
#include <thread>
bool stop = false;
long long counter = 0;
void worker() {
while (!stop) {
++counter;
}
}
int main() {
std::thread t(worker);
// ... some time later, from main, with no synchronization whatsoever:
stop = true;
t.join();
}76 of 117 in C++