Sub topic 11
RwLock for read-heavy workloads
This chapter assumes you know Arc<Mutex<T>>, lock guards, and thread::spawn with move closures. It covers RwLock, which lets many threads read shared data at the same time.
Why a Mutex can be too strict
A Mutex allows one thread at a time into the critical section, even when every thread only wants to read. If a configuration map is read thousands of times and changed once in a while, readers wait for each other for no reason. Reading does not change the data, so several readers can safely look at it together.
std::sync::RwLock<T> (read-write lock) encodes this rule:
- Any number of readers may hold the lock at once.
- A writer needs exclusive access. No readers and no other writers may hold the lock.
Using RwLock
read() returns a RwLockReadGuard, which gives shared access (Deref). write() returns a RwLockWriteGuard, which gives exclusive access (Deref and DerefMut). Both guards release the lock when they are dropped, just like a MutexGuard. Both methods return a Result, because an RwLock can be poisoned too.
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::thread;
fn main() {
let config = Arc::new(RwLock::new(HashMap::new()));
config.write().unwrap().insert("mode", "fast");
let readers: Vec<_> = (0..3)
.map(|_| {
let config = Arc::clone(&config);
thread::spawn(move || {
let map = config.read().unwrap();
map.get("mode").copied()
})
})
.collect();
for reader in readers {
println!("{:?}", reader.join().unwrap());
}
}The program first takes the write lock to insert one entry. The temporary guard is dropped at the end of that statement. Three threads then take read locks together, and each prints Some("fast").
Pitfalls
- Writer starvation. If readers keep arriving, a writer may wait a long time. The standard library does not promise a fairness policy, because it uses the operating system's lock. Behavior differs by platform.
- No upgrade path.
std::sync::RwLockhas no way to turn a read guard into a write guard. Release the read guard, then callwrite(), and check your condition again, since the data may have changed in between. - Extra bookkeeping. An
RwLocktracks readers, so it costs more per operation than aMutex. When critical sections are tiny or writes are common, a plainMutexcan be faster. - Trait bounds.
RwLock<T>isSynconly ifTis bothSendandSync.Mutex<T>needs onlyT: Send. A type that isSendbut notSync, such asCell<i32>, can go in aMutexbut not in anRwLockshared across threads.
Choosing between Mutex and RwLock
| Situation | Better choice |
|---|---|
| Many reads, rare writes, reads take noticeable time | `RwLock` |
| Frequent writes | `Mutex` |
| Very short critical sections | `Mutex` |
| Data is `Send` but not `Sync` | `Mutex` |
Measure before switching. The gain from RwLock appears only when readers truly overlap in time.
Exercise
A thread holds let r = lock.read().unwrap(); and, in the same scope, calls lock.write().unwrap() to update the value. Why is this a bug, and how do you fix it?
Show answer
The write call needs exclusive access, so it waits for every reader to finish, including the guard r held by the same thread. The thread can deadlock or panic. Fix it by dropping r (with drop(r) or an inner block) before calling write(), and recheck any condition you read earlier, because other threads may have changed the data.
Exercise
You have a Cell<i32> shared between threads through an Arc. Does Arc<RwLock<Cell<i32>>> compile when moved into thread::spawn? What about Arc<Mutex<Cell<i32>>>?
Show answer
The RwLock version does not compile, because RwLock<T> is Sync only when T is Send + Sync, and Cell<i32> is not Sync. The Mutex version compiles, because Mutex<T> is Sync when T is Send, and Cell<i32> is Send.