Sub topic 9
Mutex, RwLock and atomics make shared state safe
This chapter assumes you know what Send and Sync promise, and that Cell and RefCell are not Sync. Here you will see how the standard library gives you shared mutable state that is Sync.
Interior mutability with a safety mechanism
Cell and RefCell let you mutate through a shared reference, but they do no synchronization. Two threads could write at once, so they are not Sync.
Mutex, RwLock and the atomic types also mutate through &self. The difference is that each one enforces exclusion or uses indivisible hardware operations. That makes it safe for the standard library to mark them Sync.
| Type | `Sync` when | Why the bound |
|---|---|---|
| `Mutex<T>` | `T: Send` | Only one thread touches `T` at a time, but `T` can end up on any thread that locks it. |
| `RwLock<T>` | `T: Send + Sync` | Several readers hold `&T` at once, so `T` must be `Sync`. A writer can move `T` around, so `T` must be `Send`. |
| `AtomicUsize`, `AtomicBool`, and so on | always | Every operation is atomic, and there is no reference into the value. |
The Mutex bound is weaker than it looks
Mutex<T> needs only T: Send. A Mutex<Cell<i32>> is therefore Sync, even though Cell<i32> is not. The lock guarantees that only one thread uses the cell at a time, so the cell's missing synchronization never matters.
RwLock<Cell<i32>> is not Sync. Two readers could each hold &Cell<i32> and call set at the same moment.
All three together
This program shares an atomic counter, a mutex-guarded list and a read-mostly setting. Each is a static, which requires Sync, so the compiler checks the table above for you.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, RwLock};
use std::thread;
static HITS: AtomicUsize = AtomicUsize::new(0);
static NAMES: Mutex<Vec<String>> = Mutex::new(Vec::new());
static LIMIT: RwLock<u32> = RwLock::new(10);
fn main() {
let handles: Vec<_> = (0..4u32)
.map(|i| {
thread::spawn(move || {
HITS.fetch_add(1, Ordering::Relaxed);
NAMES.lock().unwrap().push(format!("worker-{i}"));
let limit = *LIMIT.read().unwrap();
limit + i
})
})
.collect();
let total: u32 = handles.into_iter().map(|h| h.join().unwrap()).sum();
let mut names = NAMES.lock().unwrap();
names.sort();
println!("hits = {}", HITS.load(Ordering::Relaxed));
println!("names = {:?}", *names);
println!("total = {}", total);
}The output is deterministic because the names are sorted and addition is order-independent:
hits = 4
names = ["worker-0", "worker-1", "worker-2", "worker-3"]
total = 46Choosing between them
- Use an atomic for a single integer, flag or pointer. It is lock-free and cannot be poisoned.
- Use a
Mutexwhen several fields must change together, or whenTis notSync. - Use an
RwLockwhen reads far outnumber writes andTisSync. For short critical sections aMutexis often faster, because anRwLockhas more bookkeeping.
Common mistakes
- Holding a
MutexGuardacross slow work. The guard keeps the lock held until it is dropped. AMutexGuardis also notSend, so it cannot move to another thread. - Using
Ordering::Relaxedfor an atomic that guards other data.Relaxedonly makes the single atomic operation indivisible. It does not order other memory accesses. UseAcquireandRelease, orSeqCstwhen unsure. - Calling
unwrap()onlock()without thinking about poisoning. If a thread panics while holding the lock, later calls returnErr.
Exercise
Is RwLock<Cell<i32>> Sync? Is Mutex<Cell<i32>> Sync? Explain the difference.
Show answer
RwLock<Cell<i32>> is not Sync, because RwLock<T> needs T: Send + Sync and Cell<i32> is not Sync. Several readers could hold &Cell<i32> and call set at once. Mutex<Cell<i32>> is Sync, because Mutex<T> needs only T: Send and Cell<i32> is Send. The lock allows only one thread to touch the cell at a time.