std-method
RwLock::read and write: guard selection
Read guards permit shared inspection and write guards permit exclusive mutation. Release read guards before taking a write guard. If decisions depend on the earlier state, validate the condition again after acquisition. Expected stdout (not executed): [1, 2, 3] Common mistake: Attempting a lock upgrade by holding a read guard during write acquisition.
Formal Syntax & Structure
rust syntaxrust
lock.read() -> LockResult<RwLockReadGuard<'_, T>>; lock.write() -> LockResult<RwLockWriteGuard<'_, T>>Working Example
Example Snippetrust
fn main() { use std::sync::RwLock; let state = RwLock::new(vec![1, 2]); let count = state.read().unwrap().len(); { let mut w = state.write().unwrap(); if w.len() == count { w.push(3); } } println!("{:?}", state.into_inner().unwrap());}