On this page
  1. std::atomic
  2. Overview
  3. Memory Orderings (Quick Guide)
  4. Notes & Pitfalls
  5. Example

std::atomic

Prev: std::thread | Up: concurrency | Next: io_and_filesystem
Rel: std::mutex & std::scoped_lock, jthread Work Queue Tutorial
Ref: cppreference — std::atomic
Tags: #public #prog #cpp #stdlib #concurrency #tier/standard


Overview

std::atomic<T> (<atomic>) provides data-race-free, typically lock-free operations on trivially copyable types (counters, flags, pointers) with explicit C++ memory-model orderings.

Memory Orderings (Quick Guide)

Ordering Guarantee Common Use
memory_order_seq_cst (default) Total global order across all threads Default safe choice
memory_order_acquire / release Synchronizes prior writes before release with reads after acquire Producer–consumer handoffs, spinlocks
memory_order_relaxed Atomicity only; no ordering across other variables Simple statistics counters (fetch_add)

Notes & Pitfalls

Example

#include <atomic>
#include <cassert>

int main() {
    std::atomic<int> counter{0};
    counter.fetch_add(1, std::memory_order_relaxed);
    counter.fetch_add(4, std::memory_order_relaxed);
    assert(counter.load(std::memory_order_relaxed) == 5);
}

Linked from

Related notes