std::atomic and Memory Orders
Use std::atomic with the right memory ordering for correctness and speed.
std::atomic and Memory Orders is a free C++ Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond Mutexes
Locks serialize access — they are simple and correct, but they limit throughput. std::atomic provides lock-free building blocks for high-throughput concurrent code.
std::atomic Basics
An std::atomic<T> wraps a value and supports atomic read-modify-write operations.
#include <atomic>
std::atomic<int> counter{0};
counter.fetch_add(1); // atomic increment
int v = counter.load();
counter.store(0);Convenience Operators
For arithmetic types, the usual operators are atomic.
std::atomic<int> n{0};
++n; // atomic increment
n += 5; // atomic add
int v = n; // atomic loadWhy Atomics Are Tricky
The CPU may reorder memory operations across cores. Memory order specifies which reorderings are allowed.
Memory Orders
Five common orders:
memory_order_relaxed— atomic but no orderingmemory_order_acquire— pair with release; no reorder aftermemory_order_release— pair with acquire; no reorder beforememory_order_acq_rel— bothmemory_order_seq_cst— sequentially consistent (default)
Sequential Consistency: Safe Default
The default seq_cst behaves intuitively — all atomics appear to execute in a single global order. Slower than relaxed orders but easier to reason about.
Acquire-Release Pairing
Use release in the producer and acquire in the consumer. After acquire, all writes that happened before the matching release are visible.
std::atomic<bool> ready{false};
int data = 0;
// producer
data = 42;
ready.store(true, std::memory_order_release);
// consumer
while (!ready.load(std::memory_order_acquire));
std::cout << data; // sees 42Relaxed Order
Relaxed atomics ensure atomicity (no torn reads) but allow any reordering. Use for simple counters where ordering does not matter.
Compare-and-Swap
The basis of most lock-free algorithms. compare_exchange_strong(expected, desired) updates atomically only if the current value equals expected.
std::atomic<int> a{10};
int expected = 10;
bool ok = a.compare_exchange_strong(expected, 20);
// if true, a is now 20; otherwise expected holds the actual current valueWeak vs Strong CAS
compare_exchange_weak may fail spuriously even when values match. Use it inside loops (cheaper on some platforms); use strong outside loops.
Lock-Free vs Wait-Free
Two progress guarantees:
- Lock-free — at least one thread makes progress at any time
- Wait-free — every thread makes progress in bounded time
When to Use Atomics
Atomics are not always faster than mutexes. Use them when you can keep the critical path simple — counters, flags, simple state. For complex shared state, mutexes are usually safer and clearer.
Quick Check
Which memory order has the strongest guarantees but is also the slowest?
Recap
std::atomic provides lock-free primitives with explicit memory ordering. Default to memory_order_seq_cst; use acquire/release pairs for producer-consumer patterns; relaxed only for unordered atomic operations like counters.
Frequently asked questions
Is the “std::atomic and Memory Orders” lesson free?
Yes — the full text of “std::atomic and Memory Orders” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “std::atomic and Memory Orders”?
Use std::atomic with the right memory ordering for correctness and speed. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “std::atomic and Memory Orders” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- std::atomic and Memory Orders
- Compare-and-Swap CAS Patterns
- Lock-Free Queue Implementation
- Hazard Pointers and the ABA Problem