CodeBlanks Logo Icon CodeBlanks

Acquire-release

Learn acquire-release semantics.

Acquire-release

The acquire-release model provides synchronization cheaper than seq_cst. It gives ordering only between paired release stores and acquire loads; it does not guarantee a total order.

One thread does flag.store(true, std::memory_order_release); the other, on seeing true via flag.load(std::memory_order_acquire), sees all writes the first thread did before the release. This is the common publish-then-observe pattern.

Publish-then-observe

A common use of acquire-release is the publish-then-observe pattern. Thread A prepares payload, then publishes flag with release. Thread B reads flag with acquire; on seeing true, payload is ready.

The difference from seq_cst: only this matched pair is ordered; other threads may see different order. But for most cases this is enough; performance is better.

Practice Write publish-observe with acquire-release

Define a global std::atomic<bool> flag{false}; and int payload = 0;. In main write payload = 99;, then flag.store(true, std::memory_order_release);, then bool v = flag.load(std::memory_order_acquire); and std::cout << v;.

Starter code

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

// Define the flag and payload variables here

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

Sample solution

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

std::atomic<bool> flag{false};
int payload = 0;

int main() {
    payload = 99;
    flag.store(true, std::memory_order_release);
    bool v = flag.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 store

Question
flag.store(true, std::memory_order_____);
Answer
flag.store(true, std::memory_order_release);

Explanation: release marks the writing side.

2 Match each ordering to its role

Term Meaning
store + release Write publishes
load + acquire Read sees publishes
relaxed No ordering guarantee
seq_cst Total order guarantee

3 What guarantee does the acquire-release model provide?

main.cpp
flag.store(true, release);
bool v = flag.load(acquire);
  • Ordering between paired write-read Correct answer
  • Total order across all threads
  • No ordering guarantee
  • Only single-thread order

Explanation: Acquire-release gives ordering only between paired release-acquire operations.

All lessons in Expert