Publish data with a release store and an acquire load
Hand data from one thread to another with a release store and an acquire load on a std::atomic flag, the pairing that creates happens-before.
Writing data and then setting a flag works across threads only if the flag carries ordering. A release store says "everything I wrote before this is visible to anyone who sees this value"; an acquire load that reads it says "and I will see it". Together they form a happens-before edge, and the data itself can be an ordinary non-atomic variable. Built with GCC 13, -std=c++17 -pthread.
#include <atomic>
#include <cstdio>
#include <thread>
int data = 0;
std::atomic<bool> ready{false};
int main()
{
std::thread producer([] {
data = 42; // plain write
ready.store(true, std::memory_order_release);
});
std::thread consumer([] {
while (!ready.load(std::memory_order_acquire)) {}
std::printf("data=%d\n", data); // plain read
});
producer.join();
consumer.join();
}data=42If either side used relaxed instead, the read of data would be a data race with undefined behaviour, even on x86 where the hardware would happen to behave. The guarantee holds only between the thread that releases and the thread that acquires that value; a third thread gets nothing. The spin wastes a core while it waits, so use ready.wait(false) in C++20 when the wait might be long. The rules are in std::memory_order.