Sub topic 9
Mutex, RwLock and atomics make shared state safe
This chapter assumes you know how Send and Sync are defined, that Cell and RefCell are not Sync, and that Rc is neither Send nor Sync. It also assumes you can use thread::spawn, Arc, and move closures. Here you will see how three standard library tools get around those restrictions without breaking the rules.
The problem these types solve
Cell and RefCell let you mutate data through a shared reference. They do this with no synchronization, so two threads calling set at the same time would race. The compiler stops this by making them !Sync.
Programs still need threads to change shared state. Rust's answer is to provide types that have interior mutability and are also Sync, because they coordinate access themselves. There are two approaches:
- Locks (
Mutex,RwLock) let only one thread, or only readers, touch the data at a time. - Atomics (
AtomicUsize,AtomicBool, and others) perform single operations that the hardware guarantees are indivisible.
The standard library makes Send and Sync unsafe-implemented for these types. The unsafe code is written once, inside the library, and your code stays safe.
Mutex: one thread at a time
Mutex<T> wraps a value and hands out access only through lock(). The returned MutexGuard dereferences to the value and unlocks the mutex when it is dropped.
The standard library implements the traits like this:
Mutex<T>isSendifT: Send.Mutex<T>isSyncifT: Send.
The second rule is the surprising one. T does not need to be Sync. A Mutex never gives out two references to the inner value at once. It gives one thread exclusive access at a time, so the value is effectively moved between threads in turns. That is exactly what Send describes.
This means a Mutex can make a !Sync type usable from several threads:
use std::cell::Cell;
use std::rc::Rc;
use std::sync::Mutex;
fn assert_sync<T: Sync>() {}
fn main() {
// Cell<i32> is Send, so the Mutex around it is Sync.
assert_sync::<Mutex<Cell<i32>>>();
// Rc<i32> is not Send, so a Mutex cannot save it.
// assert_sync::<Mutex<Rc<i32>>>(); // does not compile
let _ = Rc::new(1);
}A mutex cannot repair a type that is not Send. If moving the value to another thread is unsound, as with Rc, then locking it does not help.
The guard is not Send
MutexGuard<T> is Sync when T: Sync, but it is never Send. Some platforms require the thread that locked a mutex to be the one that unlocks it, so the guard must stay on its thread. This matters in two places. You cannot move a guard into thread::spawn. In async code, holding a guard across an .await can make a future non-Send, which a later chapter covers.
Poisoning
If a thread panics while holding a lock, the mutex becomes poisoned. Later calls to lock() return Err. That is why examples call unwrap(). If the data is still valid for your use, PoisonError::into_inner gives you the guard anyway.
RwLock: many readers or one writer
RwLock<T> allows any number of simultaneous read() guards, or a single write() guard. It is a better fit than Mutex when reads far outnumber writes.
Its bounds differ from Mutex:
RwLock<T>isSendifT: Send.RwLock<T>isSyncifT: Send + Sync.
Several readers hold &T at the same moment, on different threads. That is the definition of sharing a reference, so T must be Sync. A writer also needs to send values in, so T must be Send too.
| Type | `Send` when | `Sync` when |
|---|---|---|
| `Mutex<T>` | `T: Send` | `T: Send` |
| `RwLock<T>` | `T: Send` | `T: Send + Sync` |
| `AtomicUsize`, `AtomicBool`, etc. | always | always |
| `MutexGuard<'_, T>` | never | `T: Sync` |
Because of the stricter bound, RwLock<Cell<i32>> is not Sync, while Mutex<Cell<i32>> is. Concurrent readers could call Cell::set through a shared reference, which is exactly the race Cell cannot prevent.
Here is an RwLock shared by scoped threads, with three readers and one writer:
use std::sync::RwLock;
use std::thread;
fn main() {
let scores = RwLock::new(vec![10, 20, 30]);
thread::scope(|s| {
for id in 0..3 {
let scores = &scores;
s.spawn(move || {
let guard = scores.read().unwrap();
println!("reader {id} sees {} items", guard.len());
});
}
s.spawn(|| {
scores.write().unwrap().push(40);
});
});
println!("final: {:?}", scores.read().unwrap());
}Each reader prints either 3 or 4 items, depending on whether the writer ran first. The last line always prints final: [10, 20, 30, 40], because the scope joins every thread before it returns.
Atomics: indivisible single operations
Atomic types such as AtomicUsize, AtomicBool, AtomicI64 and AtomicPtr<T> are Send and Sync unconditionally. Every operation (load, store, fetch_add, compare_exchange) happens as one step that other threads cannot interrupt. No lock is involved, so there is no guard, no poisoning and no blocking.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
fn main() {
let hits = AtomicUsize::new(0);
thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
for _ in 0..1000 {
hits.fetch_add(1, Ordering::Relaxed);
}
});
}
});
println!("{}", hits.load(Ordering::Relaxed));
}This prints 4000. No updates are lost, even though fetch_add takes &self. Mutation through a shared reference is allowed here because the type is Sync by construction.
The Ordering argument controls how an operation is ordered relative to other memory operations. Relaxed guarantees only that the operation itself is atomic, which is enough for a standalone counter. If one thread writes data and another thread must see that data after reading a flag, you need Release on the store and Acquire on the load. Use SeqCst when you are unsure, and relax it only once you can prove it is safe.
Atomics have limits. They cover single machine-word values. They cannot protect a String, or keep two fields consistent with each other. Updating two atomics separately lets another thread observe one new value and one old value. For that, use a lock.
Choosing a primitive
Some practical notes:
RwLockis not always faster. Its bookkeeping costs more than aMutex, so measure before choosing it.- Keep critical sections short. Holding a guard while doing slow work blocks every other thread that needs the lock.
- Locking two mutexes in opposite orders on two threads can deadlock. Rust does not detect this, because deadlock is not a data race.
- Sharing the lock itself still needs a way to hand each thread access. Use
Arc<Mutex<T>>withthread::spawn, or plain references withthread::scope. The next chapter looks at the boundsArc<Mutex<T>>needs.
Summary of the rules
Mutex<T>needs onlyT: Sendto beSync, because it hands out one&mut-like access at a time.RwLock<T>needsT: Send + Syncto beSync, because readers share&T.- Atomics are always
SendandSync, but cover only primitive values. - Locks cannot make a non-
Sendtype such asRcthread-safe. MutexGuardis neverSend.
Exercise
Predict whether each type is Sync: (a) Mutex<Cell<u8>>, (b) RwLock<Cell<u8>>, (c) Mutex<Rc<u8>>, (d) AtomicBool. Give the reason for each.
Show answer
(a) Sync. Mutex<T> is Sync when T: Send, and Cell<u8> is Send. (b) Not Sync. RwLock<T> needs T: Send + Sync because readers share &T, and Cell<u8> is not Sync. (c) Not Sync. Rc<u8> is not Send, so Mutex<Rc<u8>> fails the T: Send requirement. (d) Sync. Atomic types are always Send and Sync.
Exercise
A worker thread needs to increment a shared request count, and another thread needs to update a shared Vec<String> of recent URLs while a third reads it. Which primitive would you use for each, and why?
Show answer
Use an AtomicUsize for the count, since it is a single integer and fetch_add needs no lock. Use a Mutex<Vec<String>> for the URL list if reads and writes are balanced, or an RwLock<Vec<String>> if reads clearly dominate. String and Vec<String> are Send and Sync, so both locks satisfy their bounds. A lock is needed because a Vec cannot be updated atomically in one hardware step.