Rust Reference ยท Standard Library Modules
Rust RwLock<T> type
Reference for std::sync::RwLock<T>: read and write guards, try_read and try_write, poisoning, writer starvation, deadlock traps and when a Mutex is the better choice.
std::sync::RwLock<T> is a reader-writer lock. Any number of threads can hold a read guard at the same time, or exactly one thread can hold a write guard, never both. Like Mutex<T>, the lock owns its data, guards release the lock on drop, and a thread that panics while holding a write guard poisons the lock.
It pays off when reads are frequent, take a noticeable amount of time and writes are rare, for example a configuration table or a cache that is read by many workers. For short critical sections a plain Mutex<T> is often just as fast, because a RwLock has more bookkeeping.
use std::sync::RwLock; let config = RwLock::new(String::from("v1")); println!("{}", config.read().unwrap());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> RwLock<T> { pub const fn new(t: T) -> RwLock<T>; pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>>; pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>>; pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>>; pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>>; pub fn is_poisoned(&self) -> bool; pub fn clear_poison(&self); pub fn into_inner(self) -> LockResult<T>; pub fn get_mut(&mut self) -> LockResult<&mut T>; }
| Name | Description |
|---|---|
read |
Blocks until no writer holds the lock; returns a shared guard (Deref). |
write |
Blocks until no one holds the lock; returns an exclusive guard (Deref and DerefMut). |
try_read, try_write |
Return immediately with TryLockError::WouldBlock if the lock is unavailable. |
Returns. Guards in a Result: Err carries a PoisonError that still contains the guard, so into_inner() gives access to the data anyway.
Errors and panics. read may panic or deadlock if the current thread already holds the write lock. Taking a second read while a writer is waiting can also deadlock on some platforms (see below).
Usage notes
Tmust beSend + SyncforRwLock<T>to be shared, because several threads access&Tat once. This is stricter thanMutex<T>, which only needsT: Send. ARwLock<Cell<i32>>cannot be shared.- No upgrade or downgrade. std has no way to turn a read guard into a write guard. Drop the read guard first, take the write lock, and re-check the condition, because the world may have changed in between.
- Recursive reads can deadlock. If a writer is already queued, some implementations block new readers to avoid starving the writer. A thread that calls
read()twice can then wait for itself. Avoid nested read locks. - Fairness is unspecified. The standard library does not promise whether readers or writers win. Do not build logic on an assumed order.
- Bind guards carefully.
let x = lock.read().unwrap().len();drops the guard at the semicolon.let g = lock.read().unwrap();keeps it until the end of the scope. - Do not hold guards across
.await, for the same reason as withMutex. - Cheap copies instead of long holds. If readers need a stable snapshot for a long time, store an
Arc<T>in the lock, clone theArcunder a short read lock, and release it. - Measure. On a short read-mostly workload a
Mutexcan win because it is simpler. ChooseRwLockfor the reasons of clarity and long read sections, then benchmark.
Related
Mutex<T>,Condvar,Arc<T>,OnceLockandLazyLock- Lessons: Mutex and RwLock, Send and Sync