Millennium · Behavioral
C++ Atomics, Memory Ordering, and Safe Publication
TrueInterview
September 26, 2026 · 2 min read
What is an atomic operation in C++, and how does std::atomic differ from using a mutex to guard shared state?
Illustrate the distinction between atomic access and ordering of other memory accesses using a shared counter and a producer that publishes a payload to a consumer. Explain why a series of atomic operations does not automatically form a single indivisible transaction.
Constraints & Assumptions
- Apply the C++ memory model and
std::atomic; do not presume that an atomic type is always lock-free. - The counter serves only for counting; its value does not signal any associated payload.
- In the publication scenario, a single producer initializes a payload once and notifies a single consumer via an atomic flag. The producer never modifies that payload after initialization.
- A hypothetical transfer between two balances demands that their combined invariant be observed consistently.
Clarifying Questions to Ask
- Does this atomic variable merely count events, or does it indicate that other data is ready?
- Are there multiple writers, and can the payload be reused or altered after publication?
- Is the requirement atomicity of a single field or a transaction spanning multiple fields?
Hint — Follow the publication edge: An atomic ready flag is beneficial only if noticing it also enforces the necessary ordering for the ordinary payload accesses.
What a Strong Answer Covers
- Indivisible operations on an atomic object, and the lack of data races on that object when accessed correctly.
- Using an atomic read-modify-write to increment a counter, instead of separate load and store operations.
- The differences between relaxed, acquire/release, and sequentially consistent ordering.
- A correct example of one-time payload publication, and why a relaxed flag is inadequate for that case.
- Why
volatile, multiple atomic fields, and “lock-free” are not replacements for the required synchronization contract.
Follow-up Questions
- Why can
counter.store(counter.load() + 1)lose increments even when both operations are atomic? - What would need to change if the producer repeatedly overwrites the published payload? Overview: Understand C++ atomics, relaxed counters, acquire-release publication, lost updates, and when multi-field invariants still demand a mutex. Read the full Millennium Software Engineer interview experience this question came from.
Loading comments…