CodeBlanks Logo Icon CodeBlanks

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.

Practice 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;.

Starter code

main.cpp
#include <iostream>
#include <atomic>

// Define the ready atomic and data variable here

int main() {
    // Set data, publish ready, load and print
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the release ordering

Question
std::atomic<int> ready{0};
ready.store(1, std::memory_order_____);
Answer
std::atomic<int> ready{0};
ready.store(1, std::memory_order_release);

Explanation: release marks the writing side.

2 When does A's write happen-before B's read?

main.cpp
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 Correct answer

Explanation: The release-acquire pairing establishes the happens-before relation.

3 Match each concept to its role

Term Meaning
sequenced-before Single-thread order
happens-before Cross-thread order
release store Write publishes
acquire load Read sees publishes

All lessons in Expert