Sub topic 12
Atomics for counters and flags
This chapter assumes you know Arc, Mutex and thread::spawn with move closures from the earlier chapters.
Why atomics exist
A Mutex<usize> protects a counter, but it makes threads wait for each other and adds lock bookkeeping. For a single integer or boolean, the CPU can do the update as one indivisible step. Rust exposes this through the types in std::sync::atomic, such as AtomicUsize, AtomicBool and AtomicI64.
An atomic operation either happens completely or not at all, as seen by every other thread. No thread can observe a half-finished update, and no lock or guard is involved.
A counter without a lock
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));
}This prints 4000. Atomic methods take &self, so you can mutate through a shared Arc without mut or a guard. You still need Arc (or scoped threads) so that every thread can reach the value.
A stop flag
An AtomicBool is a good fit for "please stop" signals.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn main() {
let stop = Arc::new(AtomicBool::new(false));
let worker_stop = Arc::clone(&stop);
let worker = thread::spawn(move || {
let mut ticks = 0u64;
while !worker_stop.load(Ordering::Relaxed) {
ticks += 1;
thread::sleep(Duration::from_millis(10));
}
ticks
});
thread::sleep(Duration::from_millis(100));
stop.store(true, Ordering::Relaxed);
let ticks = worker.join().unwrap();
println!("worker ran: {}", ticks > 0);
}The worker checks the flag on each loop and exits soon after the main thread sets it. This prints worker ran: true.
Common operations
| Method | What it does |
|---|---|
| `load` | Reads the current value |
| `store` | Writes a new value |
| `fetch_add`, `fetch_sub` | Changes the value and returns the previous one |
| `swap` | Writes a new value and returns the previous one |
| `compare_exchange` | Writes only if the current value equals the expected one |
The Ordering argument
Every operation takes an Ordering. It controls how much the compiler and CPU may reorder other memory accesses around the atomic one.
Where atomics stop working
Each operation is atomic, but a sequence of operations is not. This code has a race:
use std::sync::atomic::{AtomicUsize, Ordering};
fn racy_increment(counter: &AtomicUsize) {
let current = counter.load(Ordering::SeqCst);
counter.store(current + 1, Ordering::SeqCst); // another thread may have changed it
}Two threads can both load 5 and both store 6, losing an update. Use a single operation such as fetch_add. For custom logic, use a compare_exchange loop that retries if the value changed.
Atomics also cover only one value. If two fields must change together, for example a total and a count that must stay consistent, put them in one Mutex. Atomics are the right tool when the shared state is one number or flag and each update is a single operation.
Exercise
A teammate replaces counter.fetch_add(1, Ordering::SeqCst) with let n = counter.load(Ordering::SeqCst); counter.store(n + 1, Ordering::SeqCst);. Each call is atomic, so why can the final count be too low?
Show answer
The load and the store are two separate atomic steps. Another thread can update the counter between them. Both threads then store the same value, and one increment is lost. fetch_add performs the read and the write as one indivisible operation.
Exercise
You need to share a running total and a count of items so that readers always see matching values. Do you use two atomics or one Mutex?
Show answer
Use one Mutex around a struct holding both values. Two atomics cannot be updated together, so a reader could see the new total with the old count.