C++
std::atomic
std::memory_order
multithreading
concurrency

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.

Browse interview questions

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:

  1. Do I need the operation itself to be atomic.
  2. 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.

cpp
1#include <atomic>
2#include <iostream>
3#include <thread>
4#include <vector>
5
6int main() {
7    std::atomic<int> counter{0};
8    std::vector<std::thread> workers;
9
10    for (int i = 0; i < 4; ++i) {
11        workers.emplace_back([&counter]() {
12            for (int j = 0; j < 100000; ++j) {
13                counter.fetch_add(1, std::memory_order_relaxed);
14            }
15        });
16    }
17
18    for (auto& t : workers) {
19        t.join();
20    }
21
22    std::cout << counter.load(std::memory_order_relaxed) << '\n';
23}

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.

cpp
1#include <atomic>
2#include <iostream>
3#include <string>
4#include <thread>
5
6std::atomic<bool> ready{false};
7std::string message;
8
9void producer() {
10    message = "hello from producer";
11    ready.store(true, std::memory_order_release);
12}
13
14void consumer() {
15    while (!ready.load(std::memory_order_acquire)) {
16    }
17    std::cout << message << '\n';
18}
19
20int main() {
21    std::thread t1(producer);
22    std::thread t2(consumer);
23    t1.join();
24    t2.join();
25}

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.

cpp
1#include <atomic>
2
3std::atomic<int> state{0};
4
5void advance_state() {
6    int expected = 0;
7    state.compare_exchange_strong(
8        expected,
9        1,
10        std::memory_order_acq_rel,
11        std::memory_order_acquire
12    );
13}

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 relaxed for pure counters and metrics.
  • Use release on a writer and acquire on a reader for publication.
  • Use acq_rel for successful read-modify-write transitions that both consume and publish state.
  • Use seq_cst when 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::atomic handles atomic operations, but std::memory_order controls visibility and ordering.'
  • 'relaxed is for atomicity without synchronization of surrounding state.'
  • 'release and acquire are the usual pair for publishing data between threads.'
  • 'acq_rel fits read-modify-write state transitions.'
  • 'seq_cst is the easiest model to reason about when correctness comes first.'

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions