On this page
RwLock
Prev: `Mutex` | Up: sync | Next: `mpsc`
Rel: sync, rust/builtins
Ref: Rust std — RwLock
Tags: #public #prog #rust #stdlib #sync #tier/standard
Signature & Overview
RwLock<T>
Allows many concurrent readers (.read()) OR one exclusive writer (.write()).
Notes & Pitfalls
- Multiple concurrent readers OR one exclusive writer: Beats
Mutexonly when reads heavily outnumber writes and critical sections are non-trivial. - Never upgrade a read guard to a write guard in the same thread—that deadlocks immediately.
Example
use std::sync::RwLock;
fn main() {
let lock = RwLock::new(vec![1, 2]);
{
let r1 = lock.read().unwrap();
let r2 = lock.read().unwrap();
assert_eq!(r1.len() + r2.len(), 4);
}
lock.write().unwrap().push(3);
assert_eq!(lock.read().unwrap().len(), 3);
}
Linked from
Related notes
- tuts/rust/std/sync/mpsc Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync/Mutex Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/sync/AtomicUsize shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync/OnceLock shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier