Sub topic 11
RwLock for read-heavy workloads
This chapter assumes you know Arc<Mutex<T>>, lock guards, and how thread::spawn with move closures works. It also assumes you can read Result and unwrap. Here you will learn when RwLock is a better fit than Mutex, how to use it, and where it goes wrong.
The problem with Mutex for readers
A Mutex allows one thread inside the critical section at a time. That is the right rule when every thread writes. Many programs are different: a configuration map, a routing table, or a cache is read thousands of times for each update.
Reading does not change the data, so two readers cannot corrupt each other. A Mutex still forces them to take turns. RwLock<T> (read-write lock) relaxes the rule to match what is safe:
- Any number of threads may hold a read lock at the same time.
- Only one thread may hold the write lock, and only when no readers are active.
This is the same aliasing rule Rust applies to references: many &T or one &mut T. RwLock enforces that rule at runtime across threads.
The API
RwLock has two main methods.
| Method | Returns | Access through the guard |
|---|---|---|
| `read()` | `LockResult<RwLockReadGuard<T>>` | shared, like `&T` |
| `write()` | `LockResult<RwLockWriteGuard<T>>` | exclusive, like `&mut T` |
Both block until the lock is available. Both return a Result because an RwLock can be poisoned, as a Mutex can (see the poisoning chapter). Both guards release the lock when dropped, so the scope rules you learned for MutexGuard apply unchanged.
There are also try_read() and try_write(). They return an error at once instead of blocking when the lock is not available.
A worked example
This program shares a configuration map. One write sets it up, then three threads read it concurrently.
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());
}
}Each thread prints Some("fast").
Step by step:
Arcgives each thread shared ownership of the lock, just as withMutex.config.write()returns a write guard. The guard is a temporary, so it is dropped at the end of that statement and the lock is released.- Each reader calls
read(). All three may hold their guards at once. map.get("mode").copied()turnsOption<&&str>intoOption<&str>. The returned value does not borrow from the guard, so the guard can be dropped when the closure ends.
That last point matters. If you returned a reference into the map, it would borrow from the guard, and the compiler would reject the code because the guard dies at the end of the closure.
What the lock looks like over time
The diagram shows two readers overlapping, then a writer that must wait for both to finish.
Mutex or RwLock?
RwLock is not a faster Mutex. It does more bookkeeping, because it must track the number of readers. When critical sections are very short, that bookkeeping can cost more than the parallelism gains. Choose by workload.
| Situation | Better choice |
|---|---|
| Reads far outnumber writes, and each read holds the lock for a noticeable time | `RwLock` |
| Reads and writes are roughly balanced | `Mutex` |
| Critical section is a few instructions | `Mutex`, or an atomic |
| A single integer or flag | Atomic type |
Measure before you switch. A common mistake is replacing every Mutex with RwLock and assuming the program speeds up.
Type requirements
Mutex<T> is Sync when T: Send. RwLock<T> needs more: it is Sync only when T: Send + Sync, because several threads can hold &T at the same time. A type that is Send but not Sync, such as Cell<i32>, works inside a Mutex but not inside an RwLock shared between threads.
This follows directly from what the lock permits. With a Mutex only one thread ever touches the value at a time, so the value must be movable between threads. With an RwLock, readers touch the value concurrently, so it must also be safe to share by reference.
Edge cases and gotchas
Writer starvation and fairness
The standard library does not promise a particular policy for who gets the lock when both readers and writers are waiting. The behavior depends on the operating system's implementation. On some platforms a steady stream of new readers can delay a waiting writer. On others, a waiting writer blocks new readers. Do not write code that relies on one policy. If a writer must make progress, keep read critical sections short.
Deadlock on re-entrant reads
Taking a read lock twice on the same thread can deadlock if a writer queues between the two calls and the implementation blocks new readers behind it. The first read guard is still held, the writer waits for it, and the second read() waits behind the writer. The standard library documents that this call "might panic" or deadlock. Take the lock once and pass the guard or the data on.
use std::sync::RwLock;
fn main() {
let lock = RwLock::new(5);
let first = lock.read().unwrap();
// Taking a second read guard here while holding `first` is the risky pattern.
println!("value: {}", *first);
drop(first);
// Safe: the read guard is gone before the write lock is requested.
*lock.write().unwrap() += 1;
println!("value: {}", *lock.read().unwrap());
}The program prints value: 5 and then value: 6.
No upgrading a read guard
The standard RwLock cannot turn a read guard into a write guard. If you hold a read guard and call write() on the same thread, you wait for yourself and deadlock. Drop the read guard first, then take the write lock. Because another writer may run in between, re-check any condition you tested under the read lock.
use std::sync::RwLock;
fn main() {
let cache = RwLock::new(Vec::<u32>::new());
let needs_fill = cache.read().unwrap().is_empty();
// The read guard above was a temporary and is already dropped.
if needs_fill {
let mut guard = cache.write().unwrap();
// Re-check: another thread may have filled it in the meantime.
if guard.is_empty() {
guard.push(42);
}
}
println!("{:?}", *cache.read().unwrap());
}This prints [42]. The re-check inside the write lock is the important part.
Poisoning
An RwLock is poisoned only when a thread panics while holding the write guard. A panic while holding a read guard does not poison it, because readers cannot leave the data half-modified. Recovery uses the same into_inner method on the error as for Mutex.
Lock ordering still applies
Two RwLocks locked in opposite orders by two threads deadlock exactly as two mutexes do. Use one consistent order everywhere.
Common errors
- Holding a read guard across slow work. Writers wait for the whole duration. Copy what you need out of the guard, drop it, and then do the slow work.
- Returning references tied to the guard. Clone or copy the value out, as the example does with
copied(). - Using
RwLockwith a non-Synctype. The compiler reports that the type cannot be shared between threads safely. Use aMutexor change the type. - Using
read()and then mutating. A read guard only dereferences to&T. Mutation needswrite(), or interior mutability insideT.
Summary
RwLockpermits many readers or one writer, matching the&Tand&mut Trule.- It pays off when reads dominate and holding the read lock takes real time.
- It requires
T: Send + Sync, whileMutexrequires onlyT: Send. - Do not take a read lock while holding one, and do not try to upgrade a read guard. Drop it and take the write lock, then re-check your condition.
Exercise
A cache is read by many threads and refreshed by one thread every few minutes. A teammate proposes Arc<RwLock<Cache>>. Another teammate says Cell<u32> fields inside Cache will make the compiler reject it. Who is right, and what would you do?
Show answer
The second teammate is right about the type. RwLock<T> is Sync only if T: Send + Sync, and Cell<u32> is not Sync, so sharing Arc<RwLock<Cache>> across threads fails to compile. The RwLock design suits the workload (read-heavy, rare writes), so keep it and change the field type. Use a plain u32 that is changed only through the write guard, or an AtomicU32 if it must be updated while readers hold the lock. Using Mutex<Cache> would also compile, but it makes readers take turns.
Exercise
This code hangs. Why, and how do you fix it? let lock = RwLock::new(Vec::new()); let guard = lock.read().unwrap(); if guard.is_empty() { lock.write().unwrap().push(1); }
Show answer
The thread holds a read guard (guard) while requesting the write lock. The write lock waits until all readers release, including this thread, so it waits for itself. Fix it by dropping the read guard before calling write(), for example by computing let empty = lock.read().unwrap().is_empty(); first. Then take the write lock and re-check the condition, because another thread may have changed the data in between.