Atomic Operations in C++
Frequently Asked Questions
QWhat is the difference between memory_order_relaxed and memory_order_seq_cst?
QAre std::atomic operations always lock-free?
QWhat is the ABA problem in lock-free programming?
QWhen should I use a mutex instead of an atomic?
QCan I use std::atomic with custom types?
ATOMICS AT THE HARDWARE LEVEL Deep Dive
#include <iostream>
#include <format>
#include <atomic>
#include <thread>
#include <vector>
#include <cassert>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)
compare_exchange atomically checks a value and replaces it only if it matches.
Use CAS for lock-free algorithms, implementing custom atomics, or optimistic updates.
CAS is the fundamental building block of all lock-free data structures.
Call compare_exchange_weak in a loop (preferred on LL/SC architectures like ARM).
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
//
// 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.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)
Also, delete of old_head in pop() is unsafe if another thread still holds a pointer to it.
Also, delete of old_head in pop() is unsafe if another thread still holds a pointer to it.
A simple lock-free singly-linked stack.
Use it in code like: template<typename T>.
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
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
std::atomic_flag -- the simplest atomic type.
Use this when it cleanly solves the problem in front of you.
Only supports test-and-set / clear.
Use it in code like: class SpinLock {.
Only supports test-and-set / clear. Can build a spinlock.
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
Memory ordering demonstration.
Only use it when you just need atomicity, not synchronization.
acquire/release pair ensures proper ordering.
Follow the code pattern in this section and keep usage explicit.
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
//
// 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.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;
}