Atomics
Atomic types such as AtomicUsize offer lock-free reads and writes of a single value. You pick a memory ordering; SeqCst is the conservative default.
Detailed Explanation
A mutex around a u64 counter works and is heavier than it needs to be. AtomicU64::fetch_add(1, Ordering::Relaxed) increments without a lock. Other threads see whole values, never a torn write. That is the guarantee. It is not a mutex for a struct. You cannot make an arbitrary T atomic.
The standard atomic integers and AtomicBool / AtomicPtr live in std::sync::atomic. Operations: load, store, fetch_add, fetch_sub, compare_exchange, swap. Each takes an Ordering. Relaxed is "atomicity only, no happens-before". Acquire / Release pair a load and a store so that writes before the release become visible after the acquire. SeqCst is a single global order and is the ordering to use until you can prove a weaker one.
Wrong orderings are data races of a subtler kind: you might see the flag that says the buffer is ready and still see the old buffer contents. That is why people start with SeqCst or with Acquire on loads that check a publication flag and Release on the store that publishes.
Atomics are Send and Sync. They are the interior-mutability tool for numbers. AtomicUsize in an Arc is a shared counter. They do not replace Mutex<HashMap<K, V>>. A lock-free map is a research project or a crate, not a pile of atomics you write on a Friday.
When you reach for an atomic: flags, counters, sequence numbers, once-style state machines. When you reach for a mutex: more than one word of state that must stay consistent. When you reach for Relaxed: you have read the memory model and you are counting, not publishing.
Code Examples
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let n = Arc::new(AtomicUsize::new(0));
let mut handles = vec![];
for _ in 0..4 {
let n = Arc::clone(&n);
handles.push(thread::spawn(move || {
n.fetch_add(1, Ordering::Relaxed);
}));
}
for h in handles {
h.join().unwrap();
}
println!("{}", n.load(Ordering::Relaxed)); // prints: 4
}Common Gotchas
`Relaxed` does not publish other data
A counter increment is fine. A "ready" flag that guards a buffer needs `Release`/`Acquire`.
There is no `Atomic<String>`
Atomics are machine words (and some 128-bit platforms). Put a `String` in a `Mutex`.
`compare_exchange` is the building block of lock-free loops
It can fail because another thread won. Loop, or use `compare_exchange_weak` in a retry loop.
Do not invent a lock out of atomics unless you must
A `Mutex` is a known correct spin/wait implementation. Your flag pair probably is not.