c, stdatomic, what is stdmemory_order and how to use them?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
std::atomic gives C++ a standard way to perform thread-safe operations without always reaching for a mutex. The hard part is not creating an atomic variable, but choosing the right std::memory_order so your code is both correct and not accidentally slower than it needs to be.
What std::memory_order Controls
Two threads can both touch an atomic value and still disagree about surrounding non-atomic data unless you use ordering correctly. std::memory_order tells the compiler and CPU how much reordering is allowed around an atomic operation.
The most important orders are:
- '
std::memory_order_relaxed' - '
std::memory_order_acquire' - '
std::memory_order_release' - '
std::memory_order_acq_rel' - '
std::memory_order_seq_cst'
There is also std::memory_order_consume, but in practice it is rarely used and most codebases avoid it because compiler support and reasoning around it are weak.
Start with the Safest Mental Model
If you are new to C++ atomics, think about two separate problems:
- Do I need the operation itself to be atomic.
- Do I need other reads and writes to become visible in a particular order.
A counter often needs atomicity only. A publish-and-read pattern needs both atomicity and ordering.
memory_order_relaxed for Independent Counters
relaxed keeps the operation atomic but makes almost no promises about ordering with other memory accesses. That makes it useful for statistics counters and similar cases where exact relative ordering does not matter.
This is correct because we only care that increments are not lost. We do not use the counter to publish other state.
release and acquire for Publication
The most common non-trivial pattern is one thread preparing data and another thread reading it after a ready flag is set. The writer stores the flag with release, and the reader loads it with acquire.
If the load sees true, the read of message is guaranteed to observe the writes that happened before the release store. That is the core acquire-release contract.
acq_rel for Read-Modify-Write Operations
When one operation both reads old state and publishes new state, use std::memory_order_acq_rel. This often appears with compare_exchange or fetch_add.
Here the success ordering is acq_rel because the operation both consumes the current value and publishes a new one. The failure ordering is usually weaker.
seq_cst for Simpler Reasoning
std::memory_order_seq_cst is the strongest common choice. It gives a single global order for sequentially consistent operations, which makes reasoning easier but can add unnecessary constraints in hot paths.
If you are unsure and correctness is more important than micro-optimization, seq_cst is often a defensible first version. Then profile and reduce strength only if you can prove the weaker ordering is still correct.
Practical Selection Rules
Use these default rules unless you have a stronger reason:
- Use
relaxedfor pure counters and metrics. - Use
releaseon a writer andacquireon a reader for publication. - Use
acq_relfor successful read-modify-write transitions that both consume and publish state. - Use
seq_cstwhen you need the clearest model or are still proving correctness.
If multiple fields must change together under a real invariant, a mutex is often simpler and safer than lock-free atomics.
Common Pitfalls
The biggest mistake is assuming that std::atomic automatically makes surrounding non-atomic data safe. It does not. Another common mistake is overusing memory_order_relaxed because it benchmarks well in isolation, then relying on it for visibility guarantees it does not provide. Teams also reach for weaker orderings before they fully understand the synchronization pattern, which turns simple code into fragile code. Finally, many bugs come from forgetting that a correct atomic operation can still be part of an incorrect overall protocol.
Summary
- '
std::atomichandles atomic operations, butstd::memory_ordercontrols visibility and ordering.' - '
relaxedis for atomicity without synchronization of surrounding state.' - '
releaseandacquireare the usual pair for publishing data between threads.' - '
acq_relfits read-modify-write state transitions.' - '
seq_cstis the easiest model to reason about when correctness comes first.'
Related reading
System design interview problems on this topic
- Design a Distributed Locking System: solution and walkthrough
- Design a Distributed Counter: solution and walkthrough
- Design Ticketmaster: solution and walkthrough
- Design a Flash Sale System: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseInterview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.