EduC++ / Atomic Operations in C++

Atomic Operations in C++

Prereqs std::thread basics, understanding of data races and UB.
Standard C++11 introduced std::atomic and memory ordering. C++20 added std::atomic_ref, std::atomic<std::shared_ptr>, and wait()/notify_one()/notify_all() on atomics.

Frequently Asked Questions

QWhat is the difference between memory_order_relaxed and memory_order_seq_cst?
Arelaxed guarantees only atomicity -- the operation will not be torn, but you get no ordering guarantees relative to other operations in other threads. seq_cst (the default) provides a single total order visible to all threads, meaning every thread agrees on the sequence of seq_cst operations. seq_cst is safer but slower because it requires full memory barriers (MFENCE on x86, DMB on ARM). Use relaxed for standalone counters or statistics where ordering does not matter; use seq_cst (or acquire/release) when threads must agree on the order of events.
QAre std::atomic operations always lock-free?
ANo. An atomic is lock-free only if the CPU has native atomic instructions for that type's size and alignment. For example, std::atomic<int> and std::atomic<bool> are lock-free on virtually all modern platforms, but std::atomic<LargeStruct> may silently fall back to an internal spinlock. Check at compile time with std::atomic<T>::is_always_lock_free, or at runtime with atomic_var.is_lock_free(). If lock-freedom matters to you, static_assert on is_always_lock_free.
QWhat is the ABA problem in lock-free programming?
AThe ABA problem occurs when a CAS-based algorithm reads value A, gets preempted, another thread changes the value from A to B and back to A, and then the original thread's CAS succeeds because it still sees A -- even though the underlying state has changed. This can corrupt lock-free data structures (e.g., a freed node gets reused). Solutions include tagged pointers (appending a monotonic counter to the pointer), hazard pointers, and epoch-based reclamation.
QWhen should I use a mutex instead of an atomic?
AUse atomics for protecting a single variable with simple operations (increment, load, store, CAS). Use a mutex when you need to protect multiple variables as a single consistent unit, perform complex multi-step operations, or hold a lock across a non-trivial critical section. Atomics only protect one variable at a time and cannot express invariants spanning multiple variables.
QCan I use std::atomic with custom types?
AYes, but the type must be trivially copyable (no virtual functions, no non-trivial constructors/destructors). Even then, operations on types larger than the CPU's native word size may not be lock-free -- the implementation will use an internal lock. Always verify with is_always_lock_free if performance matters.
ATOMICS AT THE HARDWARE LEVEL Deep Dive
 

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

C++
void basic_atomic_counter() {
    std::cout << "--- Atomic Counter ---\n";
    std::atomic<int> counter{0};

    std::vector<std::thread> threads;
    for (int i = 0; i < 10; ++i) {
        threads.emplace_back([&counter] {
            for (int j = 0; j < 10'000; ++j) {
                counter.fetch_add(1);  // Atomic increment
                // Equivalent shorthand: ++counter;
            }
        });
    }

    for (auto& t : threads) t.join();

    // Always exactly 100,000 -- no data race
    std::cout << std::format("Counter: {} (expected: 100000)\n",
                              counter.load());
}

2 Compare-and-swap (CAS)

What

compare_exchange atomically checks a value and replaces it only if it matches.

When

Use CAS for lock-free algorithms, implementing custom atomics, or optimistic updates.

Why

CAS is the fundamental building block of all lock-free data structures.

Use

Call compare_exchange_weak in a loop (preferred on LL/SC architectures like ARM).

C++ Version C++11

The fundamental building block of lock-free algorithms. Atomically: if value == expected, set to desired; else load current. architectures (e.g., ARM). Always use it in a loop. compare_exchange_strong never fails spuriously but may be slower.

Watch out: compare_exchange_weak can fail spuriously on LL/SC

C++
//
// HOW IT WORKS: COMPARE-AND-SWAP AT THE HARDWARE LEVEL
//
// On x86:
//   CAS maps to the CMPXCHG instruction (with the LOCK prefix for
//   multi-core safety).  This is a *single* atomic instruction:
//     LOCK CMPXCHG [mem], desired
//   The CPU atomically reads [mem], compares it to EAX (expected),
//   and if equal, writes 'desired' to [mem].  If not equal, it loads
//   the current value into EAX.  All in one indivisible step.
//
// On ARM (and other LL/SC architectures like RISC-V, PowerPC):
//   There is no single CAS instruction.  Instead, CAS is built from
//   a Load-Linked / Store-Conditional (LL/SC) pair:
//     1. LDREX r0, [mem]     -- "load-exclusive": reads [mem] and
//                                sets a per-core "exclusive monitor"
//                                on that cache line.
//     2. CMP r0, expected    -- compare in software
//     3. STREX r1, desired, [mem]  -- "store-conditional": writes
//                                     'desired' ONLY if the exclusive
//                                     monitor is still set.  r1 = 0
//                                     on success, 1 on failure.
//
//   The exclusive monitor is cleared if *any* other core writes to
//   that cache line -- or even if an unrelated cache eviction occurs.
//   This is why compare_exchange_weak can "spuriously fail": the
//   value matched, but the STREX failed because the monitor was lost.
//
//   compare_exchange_strong wraps the LL/SC pair in a retry loop
//   internally, filtering out spurious failures.  When you are
//   already writing your own CAS loop (as in lock-free algorithms),
//   prefer compare_exchange_weak -- it avoids the double loop and
//   is more efficient on LL/SC platforms.
C++
void cas_example() {
    std::cout << "\n--- Compare-and-Swap ---\n";
    std::atomic<int> value{100};

    // Try to change 100 -> 200
    int expected = 100;
    bool success = value.compare_exchange_strong(expected, 200);
    std::cout << std::format("CAS 100->200: {} (value={})\n", success, value.load());

    // Try again: expected is 100, but value is now 200 -- fails
    expected = 100;
    success = value.compare_exchange_strong(expected, 300);
    std::cout << std::format("CAS 100->300: {} (value={}, expected updated to {})\n",
                              success, value.load(), expected);
}

3 Lock-free stack (using CAS)

What

Also, delete of old_head in pop() is unsafe if another thread still holds a pointer to it.

When

Also, delete of old_head in pop() is unsafe if another thread still holds a pointer to it.

Why

A simple lock-free singly-linked stack.

Use

Use it in code like: template<typename T>.

C++ Version Not explicitly specified in this example.

A simple lock-free singly-linked stack. real implementation needs hazard pointers or epoch-based reclamation. Also, delete of old_head in pop() is unsafe if another thread still holds a pointer to it.

Watch out: this simple lock-free stack has the ABA problem -- a

C++
template<typename T>
class LockFreeStack {
    struct Node {
        T data;
        Node* next;
        Node(T d) : data(std::move(d)), next(nullptr) {}
    };

    std::atomic<Node*> head_{nullptr};

public:
    void push(T value) {
        Node* new_node = new Node(std::move(value));
        new_node->next = head_.load();

        // CAS loop: keep trying until we successfully update head
        while (!head_.compare_exchange_weak(new_node->next, new_node)) {
            // On failure, new_node->next is updated to current head
            // automatically -- just retry
        }
    }

    bool pop(T& result) {
        Node* old_head = head_.load();

        while (old_head &&
               !head_.compare_exchange_weak(old_head, old_head->next)) {
            // Retry
        }

        if (!old_head) return false;

        result = std::move(old_head->data);
        delete old_head;
        return true;
    }

    ~LockFreeStack() {
        T dummy;
        while (pop(dummy)) {}
    }
};

4 std::atomic_flag -- the simplest atomic type

What

std::atomic_flag -- the simplest atomic type.

When

Use this when it cleanly solves the problem in front of you.

Why

Only supports test-and-set / clear.

Use

Use it in code like: class SpinLock {.

C++ Version Not explicitly specified in this example.

Only supports test-and-set / clear. Can build a spinlock.

C++
class SpinLock {
    std::atomic_flag flag_ = ATOMIC_FLAG_INIT;

public:
    void lock() {
        // Spin until we acquire the lock
        while (flag_.test_and_set(std::memory_order_acquire)) {
            // Busy-wait (in production, consider yielding or backoff)
        }
    }

    void unlock() {
        flag_.clear(std::memory_order_release);
    }
};

5 Memory ordering demonstration

What

Memory ordering demonstration.

When

Only use it when you just need atomicity, not synchronization.

Why

acquire/release pair ensures proper ordering.

Use

Follow the code pattern in this section and keep usage explicit.

C++ Version Not explicitly specified in this example.

acquire/release pair ensures proper ordering. between threads. Only use it when you just need atomicity, not synchronization. In the example below, using relaxed instead of acquire/release would make the assertion on data unreliable.

Watch out: memory_order_relaxed provides no ordering guarantees

C++
//
// HOW IT WORKS: MEMORY ORDERING
//
// Modern CPUs aggressively reorder instructions for performance:
// out-of-order execution pipelines, store buffers that delay writes,
// and write-combining buffers that batch stores.  Without explicit
// ordering constraints, a store performed on core 1 might become
// visible to core 2 in a *different order* than it was issued.
//
// The C++ memory orders map to hardware barriers:
//
//   memory_order_release (stores):
//     Flushes the store buffer -- all writes performed *before* this
//     store are guaranteed to be visible to other cores before this
//     store becomes visible.  On x86 this is usually free (stores are
//     already ordered), but on ARM it emits a DMB (data memory barrier).
//
//   memory_order_acquire (loads):
//     Prevents the compiler and CPU from reordering later reads or
//     writes *before* this load.  On x86 loads are already ordered, so
//     this is typically a compiler barrier.  On ARM it emits a DMB.
//
//   Acquire-release synchronization:
//     An acquire-load "synchronizes-with" a release-store to the same
//     atomic variable.  This creates a happens-before edge: *all*
//     writes performed before the release-store are guaranteed visible
//     to code that runs after the acquire-load reads the stored value.
//
//   memory_order_seq_cst (the default):
//     Establishes a single total order of all seq_cst operations
//     visible to every thread.  This is the safest model but also the
//     most expensive, because it typically requires a full memory
//     barrier (MFENCE on x86, DMB ISH + DSB ISH on ARM).
//
//   memory_order_relaxed:
//     Guarantees only atomicity -- the individual load or store will
//     not be torn (you will never see a half-written value).  But you
//     get *no* guarantees about when other threads see this operation
//     relative to other operations.  Use it for statistics counters
//     or progress indicators where ordering does not matter.
C++
void memory_ordering_demo() {
    std::cout << "\n--- Memory Ordering ---\n";
    std::atomic<bool> ready{false};
    int data = 0;

    std::thread writer([&] {
        data = 42;                                         // (1) Regular write
        ready.store(true, std::memory_order_release);      // (2) Release: (1) is visible before (2)
    });

    std::thread reader([&] {
        while (!ready.load(std::memory_order_acquire)) {}  // (3) Acquire: sees (2)
        // At this point, data=42 is guaranteed to be visible
        std::cout << std::format("Data: {} (guaranteed 42)\n", data);
    });

    writer.join();
    reader.join();
}

int main() {
    // 1. Basic atomic counter
    basic_atomic_counter();

    // 2. Compare-and-swap
    cas_example();

    // 3. Lock-free stack
    std::cout << "\n--- Lock-Free Stack ---\n";
    LockFreeStack<int> stack;
    {
        std::vector<std::thread> threads;
        for (int i = 0; i < 4; ++i) {
            threads.emplace_back([&stack, i] {
                for (int j = 0; j < 100; ++j) {
                    stack.push(i * 100 + j);
                }
            });
        }
        for (auto& t : threads) t.join();
    }

    int count = 0;
    int val;
    while (stack.pop(val)) ++count;
    std::cout << std::format("Popped {} items (expected: 400)\n", count);

    // 4. Spinlock
    std::cout << "\n--- SpinLock ---\n";
    SpinLock spinlock;
    int shared_counter = 0;

    {
        std::vector<std::thread> threads;
        for (int i = 0; i < 4; ++i) {
            threads.emplace_back([&] {
                for (int j = 0; j < 10'000; ++j) {
                    spinlock.lock();
                    ++shared_counter;
                    spinlock.unlock();
                }
            });
        }
        for (auto& t : threads) t.join();
    }
    std::cout << std::format("SpinLock counter: {} (expected: 40000)\n",
                              shared_counter);

    // 5. Memory ordering
    memory_ordering_demo();

    return 0;
}