Hard
Handing off data with a release and an acquire
producer() writes a plain (non-atomic) int data, then does a release-store to std::atomic<bool> ready. consumer() spin-waits with an acquire-load on ready. Once consumer observes ready == true, is it guaranteed to see data == 42, with no UB? And what would break if both the store and the load instead used memory_order_relaxed?
main.cpp
#include <atomic>
#include <thread>
std::atomic<bool> ready{false};
int data = 0;
void producer() {
data = 42; // plain, non-atomic write
ready.store(true, std::memory_order_release);
}
void consumer() {
while (!ready.load(std::memory_order_acquire)) {
// spin
}
// is data guaranteed to be 42 here?
}75 of 117 in C++