Study guides · Intermediate

Read memory ordering through publication and synchronization

Execute one-shot release/acquire publication and distinguish atomic indivisibility, reads-from relations, language rules and machine observations.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Identify the relation between different variables
  2. Connect release and acquire through an observed publication
  3. Keep atomicity distinct from cross-object ordering
  4. Run five hundred one-shot publications
  5. Move between language and processor models carefully
  6. Check lifetime beyond the atomic flag
  7. Distinguish independent repetitions from a reused flag
  8. Give every diagram edge a meaning
  9. Exercise: identify the publication actually observed
  10. Ask Logeia about this articleCheck your understanding

Identify the relation between different variables

A producer writes42 to data and then one to ready. A consumer waits until ready is one before reading data. Source order alone is not a sufficient explanation of what another thread must observe. Identify synchronization and which write a read obtains its value from. Wall-clock timestamps and diagnostic print order do not replace those relations.

The example uses C++ atomics for both variables. An acquire read that actually observes the release publication can connect the producer's earlier operations with the consumer's later operations. We do not execute a racy non-atomic variant as a benchmark. Undefined behavior from a data race and weaker ordering among valid atomic operations are different topics. Establish the language model before interpreting observations on one processor.

Connect release and acquire through an observed publication

The producer first performs a relaxed data store, then a release store of one to ready. If the consumer's acquire load reads that publication, its later relaxed data load is ordered after the earlier data write. An acquire label does not automatically connect to every release elsewhere. The atomic object and the write supplying the read value matter. A single zero-to-one publication keeps that relation explicit.

Resetting and reusing ready introduces generations, reuse of data and acknowledgment of consumption. The one-shot example is not automatically a reusable mailbox. Additional ownership and completion rules need their own ordering argument. Finding one valid synchronization pair does not prove the lifetime and reuse protocol of an entire concurrent structure.

OrderProducerConsumer
1Write 42 to dataInspect ready with acquire
2Store 1 to ready with releaseRead data after observing that publication
3Keep lifetime through joinAssert data equals 42

Keep atomicity distinct from cross-object ordering

Relaxed does not remove atomic indivisibility or all rules for one atomic object. It does not by itself create the cross-variable publication guarantee required here. With both data and ready atomic and relaxed, reason from the language model about which outcome is permitted. Failure to observe a stale value on one machine does not establish that every allowed execution forbids it.

Do not turn data non-atomic merely to make a dramatic failing demonstration. Without synchronization, conflicting accesses can introduce undefined behavior rather than a meaningful weak-order observation. Compare defined programs with explicit memory orders. Saving source, compiler and ISA improves reproducibility, but increasing trial count still cannot enumerate all executions permitted by the language model. Formal allowance and empirical occurrence are separate conclusions.

Run five hundred one-shot publications

Each iteration creates fresh atomic data and ready values and launches one producer and one consumer. The consumer waits for an acquire read of one, then asserts data is42. Join both threads before destroying the variables and beginning another iteration. Compile as C++17 with optimization, warnings and pthread support. Save compiler, OS and exit status with the run.

Passing this executable is evidence for this example on the recorded environment; the synchronization argument also explains why it is valid. The run does not measure how frequently an all-relaxed variant exposes a stale value. Its output says so explicitly. Yielding in the loop is a readable waiting mechanism here, not a performance recommendation. Production waiting requires a separate choice based on CPU use and latency requirements.

cpp
#include <atomic>
#include <cassert>
#include <iostream>
#include <thread>
int main(){
    for(int round=0;round<500;++round){
        std::atomic<int> data{0},ready{0};
        std::thread producer([&]{data.store(42,std::memory_order_relaxed);ready.store(1,std::memory_order_release);});
        std::thread consumer([&]{while(ready.load(std::memory_order_acquire)==0)std::this_thread::yield();assert(data.load(std::memory_order_relaxed)==42);});
        producer.join();consumer.join();
    }
    std::cout<<"500 release/acquire publications passed; no relaxed-outcome exclusion claimed\n";
}

Move between language and processor models carefully

Compiler transformations and processor execution both matter, but begin with relations guaranteed by the language. A particular ISA's stronger observed ordering does not supply missing portable synchronization under every compiler and target. Disassembly documents generated instructions for one build; it does not independently define every source-level allowed execution.

When connecting to out-of-order execution, keep issue/retirement order, cross-core observation and C++ happens-before distinct. They belong to different model layers. A diagram should label program order, reads-from and synchronization rather than using one undifferentiated arrow. Physical time alone cannot identify the write a load observed or establish that an accessed object's lifetime remains valid. Use each layer to explain its own guarantees and observations.

Check lifetime beyond the atomic flag

Correct publication order does not help if the data object is destroyed before the reader uses it. Publishing a pointer also needs lifetime and mutation-ownership rules. Atomic storage of a pointer does not make every operation on the pointed-to object atomic. Safe reclamation is an additional protocol, connected to the reclamation guide rather than silently supplied by the ready flag.

A lock can be clearer when it protects one shared invariant and its associated lifetime. This lesson does not recommend weaker orders as an optimization goal in themselves. State the required guarantee, implement an understandable correct protocol and evaluate alternatives only against a measured need. Fewer generated instructions and faster application behavior are not automatically the same result. Ordering choices belong within the whole ownership and correctness argument.

Distinguish independent repetitions from a reused flag

Resetting a one-shot flag and reusing it creates a generation problem. The reader must know whether the observed one published the current data or belongs to an earlier round. A producer overwriting data before reader completion also changes ownership after publication. Merely placing acquire and release somewhere does not associate every generation correctly.

A sequence number, queue or ownership-transfer protocol can define the correspondence, with its own wraparound and delayed-reader assumptions. The five hundred executions here create fresh variables and threads and join them each round. They are independent one-shot repetitions, not verification of a reusable mailbox. Two loops can look similar while relying on different lifetime boundaries. State which resources are destroyed between attempts and which remain shared before transferring evidence from a bounded test to a continuing service.

Identify the publishing store that the load actually observes. A flag name alone does not establish which data publication, if any, supplies the required synchronization relation.

Give every diagram edge a meaning

Label the producer's data-store-to-ready edge as its in-thread order. Label the edge from the published ready store to the consumer load that observes it with the synchronization condition. Then connect the consumer's later data load. A timeline with undifferentiated arrows can hide exactly which missing condition breaks the argument.

Replace the acquiring ready load with an acquire on an unrelated atomic in an exercise. If it does not observe the publication, spelling acquire does not supply the needed connection. Return the definition's reads-from requirement to concrete events. Use the diagram to locate assumptions and counterexamples, not to decorate a conclusion. Source code, event labels and quiz conditions should describe the same one-shot publication. This makes the proof boundary inspectable even when machine execution times are not being measured.

Exercise: identify the publication actually observed

If the consumer's acquire load reads the producer's release of one after storing42, the later data load returns42 in this one-shot example, assuming no intervening writers and valid lifetime. Draw the relation through that particular ready write and read. An unrelated acquire on another flag cannot simply be substituted because its spelling looks similar.

If an all-relaxed atomic variant returns42 in five hundred trials, that does not prove release/acquire unnecessary: the observation does not eliminate other executions allowed by the language. Likewise a racy non-atomic failure is not equivalent evidence about a defined weak-order program. Explain model, observed publication, lifetime and empirical scope together. Those distinctions support reasoning beyond a machine-specific anecdote.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 17

Understand the systems behind the web · STEP 7

Prepare for AI systems · STEP 7

Choose a learning path