Skip to content

std::atomic (C++11) ​

In a nutshell ​

A template class that guarantees read and write operations are indivisible, so that multiple threads accessing the same variable concurrently never produce a data race.

Header file ​

#include <atomic>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructoratomic() noexcept = default;Default construction (value left uninitialized)
AssignmentT operator=(T desired) noexcept;Atomically writes the given value
Readoperator T() const noexcept;Atomically reads and returns the current value
Storevoid store(T desired, memory_order order = memory_order_seq_cst) noexcept;Atomic write
LoadT load(memory_order order = memory_order_seq_cst) const noexcept;Atomic read
ExchangeT exchange(T desired, memory_order order = memory_order_seq_cst) noexcept;Atomically replaces the old value and returns it
Compare exchangebool compare_exchange_weak(T& expected, T desired, ...) noexcept;Weak CAS; may fail spuriously
Compare exchangebool compare_exchange_strong(T& expected, T desired, ...) noexcept;Strong CAS; fails only on a genuine mismatch
Atomic addT fetch_add(T arg, memory_order order = memory_order_seq_cst) noexcept;Atomically adds and returns the previous value (integers/pointers)
Lock-free checkbool is_lock_free() const noexcept;Checks whether this type is implemented lock-free

Minimal Example ​

C++
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

std::atomic<int> cnt{0};

int main() {
    std::vector<std::jthread> pool;
    for (int i = 0; i < 10; ++i)
        pool.emplace_back([] { for (int n = 0; n < 10000; ++n) cnt++; });
    std::cout << cnt << '\n'; // outputs 100000
}

Embedded Suitability: High ​

  • Properly aligned integer and pointer types usually map straight onto hardware atomic instructions, with zero extra overhead
  • is_lock_free() lets us confirm at runtime whether the implementation is truly lock-free, avoiding hidden system calls
  • A lean replacement for heavyweight mutexes, well suited to lightweight state synchronization between an interrupt handler and the main loop
  • Oversized custom structs may fall back to an internally locked implementation — the main pitfall to watch out for

Compiler Support ​

GCCClangMSVC
4.43.119.0

See Also ​


Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05