Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::atomic class template

Reference for std::atomic: load, store, exchange, fetch_add, compare_exchange_weak and strong, atomic_flag, is_lock_free and how atomics avoid data races.

std::atomic<T> (header <atomic>) wraps a value so that reads, writes and read-modify-write operations on it happen as indivisible steps. Two threads using atomic operations on the same object never cause a data race, so you can share a counter, a flag or a pointer between threads without a mutex.

Atomics work for integers, pointers, bool, floating-point types and any trivially copyable type (those larger than a few machine words may use an internal lock). The operators ++, +=, &= and friends on integer atomics are atomic too. Each operation takes an optional memory order; the default, memory_order_seq_cst, is the safest.

C++
std::atomic<int> hits{0};
hits.fetch_add(1);          // atomic increment
++hits;                     // same thing
int now = hits.load();

Try it

C++ A counter that needs no mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ exchange, compare_exchange and a CAS loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class T> struct atomic {
    atomic() noexcept;                               // value-initialized since C++20
    constexpr atomic(T desired) noexcept;
    atomic(const atomic&) = delete;

    T    load(std::memory_order = std::memory_order_seq_cst) const noexcept;
    void store(T desired, std::memory_order = std::memory_order_seq_cst) noexcept;
    T    exchange(T desired, std::memory_order = std::memory_order_seq_cst) noexcept;
    bool compare_exchange_weak(T& expected, T desired,
                               std::memory_order = std::memory_order_seq_cst) noexcept;
    bool compare_exchange_strong(T& expected, T desired,
                                 std::memory_order = std::memory_order_seq_cst) noexcept;
    bool is_lock_free() const noexcept;

    // integral and pointer specializations also have:
    // fetch_add, fetch_sub, fetch_and, fetch_or, fetch_xor, operators ++ -- += -= &= |= ^=
    // C++20: wait(old), notify_one(), notify_all()
};
Name Description
load / store Read or write the value atomically.
exchange Stores a new value and returns the previous one.
compare_exchange_* If the current value equals expected, stores desired and returns true; otherwise copies the current value into expected and returns false.
fetch_add etc. Apply the operation and return the old value. The operators (+=, ++) return the new value.
wait / notify_* C++20: sleep until the value differs from old, and wake sleepers.

Returns: see the table. Errors: none are thrown. Passing an invalid memory order (for example memory_order_acquire to store) is undefined behavior.

Usage notes

  • Atomic is not the same as thread-safe code. Each operation is safe, but a sequence such as if (a.load() == 0) a.store(1); is a race of the check-then-act kind. Use compare_exchange for it.
  • compare_exchange_weak may fail spuriously and is the better choice in loops; _strong does not fail spuriously and suits one-shot attempts.
  • Atomics cannot be copied. Initialize with std::atomic<int> a{0}; (the = 0 form works since C++17); use load() to copy the value.
  • Only whole objects are atomic. std::atomic<std::vector<int>> is not allowed (not trivially copyable). Atomic smart pointers exist: std::atomic<std::shared_ptr<T>> (C++20).
  • Floating point: fetch_add on atomic<double> exists since C++20; the order of additions across threads is unspecified, so the sum may differ in the last digits.
  • atomic_flag is the only type guaranteed lock-free. test_and_set returns the previous state; test() and wait() were added in C++20.
  • std::atomic_ref<T> (C++20) gives atomic access to an ordinary variable for the lifetime of the reference.
  • Cost: a relaxed atomic increment is a single instruction on x86; sequentially consistent stores are slower; heavily contended atomics still bounce a cache line between cores.