C++
Happens-before
Learn the happens-before relationship.
Happens-before
The happens-before relation is an ordering that says the result of an operation in one thread is visible to another. If A happens-before B, then B always sees A's effect.
A common way to establish happens-before across threads is the release-acquire pair: thread A does flag.store(1, std::memory_order_release); thread B reads with flag.load(std::memory_order_acquire). When B sees 1, all of A's writes before the release become visible.
Establishing ordering
Without establishing happens-before, there is no ordering between two threads: one writes, the other reads, but the reader may see the old value forever. std::memory_order_relaxed only provides atomicity, not ordering.
Release-acquire gives ordering. A writes data = 42; then does ready.store(1, release). When B sees 1 via ready.load(acquire), it is guaranteed to see data as 42. This is the publish-then-observe pattern.
Exercise Establish happens-before with release-acquire
Define a global std::atomic<int> ready{0}; and int data = 0;. In main write data = 42;, then ready.store(1, std::memory_order_release);, then int v = ready.load(std::memory_order_acquire); and std::cout << v;.
Show example solution
#include <iostream>
#include <atomic>
std::atomic<int> ready{0};
int data = 0;
int main() {
data = 42;
ready.store(1, std::memory_order_release);
int v = ready.load(std::memory_order_acquire);
std::cout << v;
return 0;
}
Test yourself
-
Complete the release ordering
std::atomic<int> ready{0};
ready.store(1, std::memory_order_____);
Show answer
std::atomic<int> ready{0};
ready.store(1, std::memory_order_release);
-
When does A's write happen-before B's read?
Thread A: data = 42; ready.store(1, release);
Thread B: if (ready.load(acquire)) use(data);
- Always
- Only if B finishes before A starts
- If both are on the same CPU core
- A does release, B does acquire, and B sees the release
Show answer
A does release, B does acquire, and B sees the release — The release-acquire pairing establishes the happens-before relation.
-
Match each concept to its role
- sequenced-before
- Single-thread order
- happens-before
- Cross-thread order
- release store
- Write publishes
- acquire load
- Read sees publishes
Next lesson: Sequential consistency