Mutex and RwLock
Quick answer
A Mutex grants exclusive access while its guard lives. An RwLock allows multiple readers or one writer, but not both simultaneously.
Keep critical sections small
A guard releases the lock on drop. Standard locks can block the calling thread. Mutex poisoning indicates a possible broken invariant after a panic; RwLock poisoning normally follows a panic while holding a write guard. Recovery requires checking or repairing the protected state, not just ignoring the error. Reader/writer scheduling policy is platform dependent.
use std::sync::Mutex;fn main() { let count = Mutex::new(0); std::thread::scope(|s| { for _ in 0..3 { s.spawn(|| *count.lock().unwrap() += 1); } }); println!("{}", *count.lock().unwrap());}Expected stdout (not executed):
3Each update occurs under the exclusive lock.
use std::sync::RwLock;fn main() { let settings = RwLock::new(vec![1]); { settings.write().unwrap().push(2); } let read = settings.read().unwrap(); println!("{}", read.len());}Expected stdout (not executed):
2The write guard has been released before reading.
Common mistake
Do not assume RwLock always outperforms Mutex; measure contention and workload.
Try it yourself
Protect a Vec of worker results and check its final length after joining.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mutex and RwLock — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A worker panics while holding a Mutex guard. What should recovery consider?
Mutex and RwLock — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::sync::Mutex; fn main() { let count = Mutex::new(0); std::thread::scope(|s| { for _ in 0..3 { s.spawn(|| *count.lock().unwrap() += 1); } }); println!("{}", *count.lock().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Mutex and RwLock — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::sync::RwLock; fn main() { let settings = RwLock::new(vec![1]); { settings.write().unwrap().push(2); } let read = settings.read().unwrap(); println!("{}", read.len()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.