std::atomic
Prev: std::thread | Up: concurrency | Next: io_and_filesystem
Rel: std::mutex & std::scoped_lock, jthread Work Queue Tutorial
Ref: cppreference — std::atomic
Tags: #public #prog #cpp #stdlib #concurrency #tier/standard
Overview
std::atomic<T> (<atomic>) provides data-race-free, typically lock-free operations on trivially copyable types (counters, flags, pointers) with explicit C++ memory-model orderings.
Memory Orderings (Quick Guide)
| Ordering | Guarantee | Common Use |
|---|---|---|
memory_order_seq_cst (default) |
Total global order across all threads | Default safe choice |
memory_order_acquire / release |
Synchronizes prior writes before release with reads after acquire | Producer–consumer handoffs, spinlocks |
memory_order_relaxed |
Atomicity only; no ordering across other variables | Simple statistics counters (fetch_add) |
Notes & Pitfalls
- Lock-free shared primitives: Default
std::memory_order_seq_cstis safest; drop torelaxedoracquire/releaseonly after profiling. - Only trivially copyable types can be wrapped in
std::atomic<T>.
Example
#include <atomic>
#include <cassert>
int main() {
std::atomic<int> counter{0};
counter.fetch_add(1, std::memory_order_relaxed);
counter.fetch_add(4, std::memory_order_relaxed);
assert(counter.load(std::memory_order_relaxed) == 5);
}
Linked from
Related notes
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/thread Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #stdlib
- tuts/cpp/tutorials/jthread_work_queue_and_atomics Linked here; links to this page; shared tags: #concurrency, #cpp, #prog, #tier
- tuts/cpp/stdlib/io_and_filesystem Linked here; shared tags: #cpp, #prog, #stdlib
- tuts/cpp/stdlib/concurrency/jthread shared tags: #concurrency, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/find_if shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/transform shared tags: #cpp, #prog, #stdlib, #tier