`RwLock`
RwLock<T> allows many concurrent readers or one writer. read and write return guards that release the lock when they drop.
Detailed Explanation
A reader-writer lock distinguishes shared reads from exclusive writes. read() blocks only if a writer holds the lock. Many RwLockReadGuards can exist at once. write() blocks until every reader and writer is gone, then hands out a single RwLockWriteGuard. That is the win over Mutex when the common path is read-only.
The cost is a more expensive lock and a policy question about writers. Std's RwLock on some platforms can starve writers if readers keep arriving. Do not assume fairness. If writes are frequent, a Mutex is often faster because you skip the reader-count machinery.
Poison works like Mutex: a panic while holding a write guard poisons the lock. A panic while holding a read guard does not, because readers do not mutate. Check the LockResult.
RwLock is still not RefCell. It is for threads. On a single thread, RefCell is cheaper. In async code, tokio::sync::RwLock is the type that is safe to hold across .await (and even then, holding a write lock across a long await is a throughput bug).
When you reach for RwLock: a config or cache that many threads read and few update. When you reach for Mutex: mixed or write-heavy access, or a simple critical section. When you reach for atomics: a counter or flag, not a struct.
Upgrade paths are missing: you cannot turn a read guard into a write guard without releasing the read lock first. Between the drop and the write another writer can run. If that window is a bug, start with a write lock, or re-check the invariant after you acquire it. Some crates offer upgradable guards; std does not.
Code Examples
use std::sync::RwLock;
fn main() {
let table = RwLock::new(vec!["ada"]);
{
let read = table.read().unwrap();
println!("{}", read[0]); // prints: ada
}
table.write().unwrap().push("grace");
println!("{}", table.read().unwrap().len()); // prints: 2
}Common Gotchas
Writer starvation is possible
A constant stream of readers can delay `write` indefinitely on some implementations. Batch reads, or use a mutex if writes must proceed.
A read guard and a write guard in the same thread deadlock
Drop the read guard before you `write`. `std::sync::RwLock` is not recursive.
Poison is for write panics
Do not assume a read-side panic poisons. Repair logic belongs on the write path.
Read-heavy is a measurement, not a guess
If you write on every request, `RwLock` is extra cost for no concurrency.