A deadlock occurs when code waits forever for a lock that cannot become available. With a Mutex, locking creates a MutexGuard, and the lock remains held until that guard is dropped or leaves its scope. section 10.3.3
Locking the same Mutex twice
After mutex_changer locks my_mutex, a second call to my_mutex.lock().unwrap() waits for the first guard to disappear. Because the first guard remains alive, the program never reaches the following println! statement. section 10.3.3
use std::sync::Mutex;
fn main() {
let my_mutex = Mutex::new(5);
let mut mutex_changer = my_mutex.lock().unwrap(); #1
let mut other_mutex_changer = my_mutex.lock().unwrap(); #2
println!("This will never print...");
}
This minimal Rust listing shows a guard holding a Mutex while a second lock attempt waits forever. section 10.3.3
Avoid a deadlock by controlling how long access remains held:
- Put the guard in its own scope or call drop(guard) before requesting the lock again. section 10.3.3 section 10.3.4
- Use try_lock() when giving up is preferable to waiting indefinitely; handle its success or failure with if let or match. section 10.3.3
- Apply the same approach to RwLock: release read guards before requesting write access, or use try_read() and try_write(). section 10.3.4














