Sub topic 12
Atomics for counters and flags
This chapter assumes you can already use Arc, thread::spawn with move closures, and Mutex. It covers atomic types, which let threads share a single integer or boolean without a lock. It also covers when atomics are the wrong tool.
Why atomics exist
A counter behind Arc<Mutex<usize>> works, but every increment locks, unlocks, and may make other threads wait. For one integer, that is more machinery than the job needs.
An atomic type is a value whose reads and writes the CPU performs as one indivisible step. No thread can see a half-finished update. Atomics live in std::sync::atomic:
AtomicBoolAtomicUsize,AtomicIsizeAtomicU8throughAtomicU64, and the signedAtomicI8throughAtomicI64
Atomic methods take &self, not &mut self. A shared reference is enough to modify the value, which is why an Arc<AtomicUsize> can be changed from many threads with no lock. This is called interior mutability, the same idea behind Mutex.
A lock-free counter
This replaces Arc<Mutex<usize>> from earlier chapters.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let hits = Arc::new(AtomicUsize::new(0));
let handles: Vec<_> = (0..4)
.map(|_| {
let hits = Arc::clone(&hits);
thread::spawn(move || {
for _ in 0..1000 {
hits.fetch_add(1, Ordering::Relaxed);
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("{}", hits.load(Ordering::Relaxed));
}The program prints 4000. fetch_add reads the old value, adds 1, and writes the result as a single atomic operation. It returns the old value. Two threads can never read the same old value and both write back old + 1, which is the lost-update bug from the shared-state chapter.
Atomic integers wrap on overflow in fetch_add and fetch_sub. They do not panic, even in debug builds.
The Ordering argument
Every atomic method takes an Ordering. It tells the compiler and CPU how much they may reorder other memory operations around this one.
| Ordering | Guarantee | Typical use |
|---|---|---|
| `Relaxed` | The operation itself is atomic. No promises about other memory. | Independent counters, statistics |
| `Acquire` | On a load, later reads and writes cannot move before it. Pairs with a `Release` store. | Reading a "ready" flag |
| `Release` | On a store, earlier reads and writes cannot move after it. | Setting a "ready" flag |
| `AcqRel` | Acquire and release together, for read-modify-write operations. | `compare_exchange` |
| `SeqCst` | Acquire and release, plus one global order that all threads agree on. | When unsure |
Relaxed is correct for the counter above. Each increment is atomic, and nothing else depends on seeing the counter at a particular moment. The join calls already guarantee that the main thread sees all the increments. Joining a thread synchronizes with everything that thread did.
If you cannot explain why a weaker ordering is safe, use SeqCst. It costs slightly more on some CPUs, and it is the safest default.
A stop flag
A common use of AtomicBool is telling a background thread to quit.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn main() {
let stop = Arc::new(AtomicBool::new(false));
let ticks = Arc::new(AtomicU64::new(0));
let worker = {
let stop = Arc::clone(&stop);
let ticks = Arc::clone(&ticks);
thread::spawn(move || loop {
ticks.fetch_add(1, Ordering::Relaxed);
if stop.load(Ordering::Relaxed) {
break;
}
thread::sleep(Duration::from_millis(1));
})
};
thread::sleep(Duration::from_millis(20));
stop.store(true, Ordering::Relaxed);
worker.join().unwrap();
println!("ticked at least once: {}", ticks.load(Ordering::Relaxed) >= 1);
}The program prints ticked at least once: true. The worker ticks before it first checks the flag, so the count is at least 1 on every run.
Relaxed is enough here because the flag carries no other data. The worker only needs to notice the change eventually.
When the flag publishes data
A flag often means "the data is ready". Then the ordering matters, because the reader must also see the data the writer prepared. The writer stores the flag with Release. The reader loads it with Acquire. If the reader sees true, it is guaranteed to see every write the writer made before the store.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let payload = Arc::new(AtomicU64::new(0));
let ready = Arc::new(AtomicBool::new(false));
let producer = {
let payload = Arc::clone(&payload);
let ready = Arc::clone(&ready);
thread::spawn(move || {
payload.store(42, Ordering::Relaxed);
ready.store(true, Ordering::Release);
})
};
while !ready.load(Ordering::Acquire) {
std::hint::spin_loop();
}
println!("payload: {}", payload.load(Ordering::Relaxed));
producer.join().unwrap();
}The program always prints payload: 42. With Relaxed on the flag, the reader could in principle see true and still read 0, depending on the CPU.
The spin loop burns a core while it waits. For anything that waits longer than a few microseconds, use Condvar or a channel instead. Both are covered in later chapters.
Compare-and-exchange
fetch_add covers simple arithmetic. For anything else, use compare_exchange. It writes a new value only if the current value equals what you expect, and it reports success or failure as one atomic step.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
const NO_WINNER: usize = usize::MAX;
fn main() {
let winner = Arc::new(AtomicUsize::new(NO_WINNER));
let handles: Vec<_> = (0..4)
.map(|id| {
let winner = Arc::clone(&winner);
thread::spawn(move || {
winner
.compare_exchange(NO_WINNER, id, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
})
})
.collect();
let wins = handles
.into_iter()
.map(|h| h.join().unwrap())
.filter(|&won| won)
.count();
println!("threads that won: {}", wins);
println!("winner recorded: {}", winner.load(Ordering::Acquire) != NO_WINNER);
}The program prints threads that won: 1 and winner recorded: true. Which thread wins varies between runs, but exactly one does.
compare_exchange takes two orderings. The first applies on success, and the second applies to the load when it fails. The failure ordering cannot be stronger than the success ordering, and it cannot be Release or AcqRel.
When the new value is computed from the old one, fetch_update retries the compare-and-exchange for you:
use std::sync::atomic::{AtomicUsize, Ordering};
fn main() {
let peak = AtomicUsize::new(10);
for sample in [4, 25, 17] {
let _ = peak.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(current.max(sample))
});
}
println!("peak: {}", peak.load(Ordering::SeqCst));
}The program prints peak: 25. The closure may run more than once if another thread changes the value in between, so it must have no side effects. For a plain maximum, fetch_max does the same job in one call.
Atomics without Arc
An atomic with a constant initializer can be a static. Every thread can reach it by name, so no Arc is needed:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
fn next_id() -> usize {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
fn main() {
let handles: Vec<_> = (0..3).map(|_| thread::spawn(next_id)).collect();
let mut ids: Vec<usize> = handles.into_iter().map(|h| h.join().unwrap()).collect();
ids.sort();
println!("{:?}", ids);
}The program prints [1, 2, 3]. Every thread gets a unique ID. Unique ID generation is one of the most common real uses of atomics.
Limits of atomics
An atomic protects one operation on one value. Two correct atomic operations in a row are not atomic together.
use std::sync::atomic::{AtomicUsize, Ordering};
fn withdraw_wrong(balance: &AtomicUsize, amount: usize) -> bool {
// Race: another thread can change balance between the load and the store.
if balance.load(Ordering::SeqCst) >= amount {
balance.fetch_sub(amount, Ordering::SeqCst);
true
} else {
false
}
}
fn main() {
let balance = AtomicUsize::new(100);
println!("{}", withdraw_wrong(&balance, 30));
}This compiles and prints true single-threaded. With several threads, two of them can both pass the check and drive the balance below zero, which wraps around to a huge number. The fix is a fetch_update that performs the check inside the closure, or a Mutex around the whole operation.
Use a Mutex instead of atomics when:
- Several fields must change together to keep an invariant, such as a balance and a transaction log.
- The data is not a single integer or boolean (a
Vec, aString, a struct). - You find yourself reasoning about orderings you cannot justify.
Atomics have no lock guard, so there is no poisoning and no deadlock. The risk is subtle logic errors, which the compiler cannot catch.
Choosing a tool
Common errors
- Using
Relaxedfor a flag that guards data. The reader can see the flag without seeing the data. UseReleaseon the store andAcquireon the load. - Check-then-act with separate calls. A
loadfollowed by astoreis a race. Usecompare_exchange,fetch_update, or aMutex. - Ignoring wraparound.
fetch_subon anAtomicUsizeat 0 wraps tousize::MAX. - Spinning for a long wait. A
while !flag.load(..)loop with no sleep uses a full core. UseCondvaror a channel. - Expecting
Rc-like behavior. An atomic is not a pointer. To share one between threads you still need anArc, astatic, or a scoped-thread borrow.
Exercise
Four threads each call fetch_add(1, Ordering::Relaxed) 1000 times on a shared AtomicUsize. After joining all four, the main thread loads the value with Ordering::Relaxed. Is it guaranteed to read 4000? Then, a thread sets ready.store(true, Ordering::Relaxed) after writing a Vec into a Mutex-free shared structure. Why is that flag unsafe for publishing the data, and which two orderings fix it?
Show answer
Yes, it reads 4000. fetch_add is atomic under any ordering, so no increment is lost, and join makes each thread's work visible to the main thread. The second flag is unsafe because Relaxed gives no ordering between the data writes and the flag write, so a reader can see true before it sees the data. Store the flag with Ordering::Release and load it with Ordering::Acquire. A reader that sees true then also sees every write made before the store.