liveBook · Manning

Deadlock

As explained in Learn Rust in a Month of Lunches

A deadlock is a state in which threads or operations wait indefinitely for access held by one another.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the waiting mechanism, demonstrates repeated locking, and gives scope, drop(), and try-method remedies.
Examples
Shows repeated Mutex locking, scoped guards, drop(), try_lock(), and RwLock read-then-write access.
What it assumes
Introduces Mutex and RwLock locking behavior while relying on basic Rust variables, scopes, methods, and pattern matching.
What you can do after
Diagnose/debug with it by identifying held guards and prevent indefinite waits with scopes, drop(), or try-lock methods.
How it connects
Connects deadlock to Mutex, MutexGuard, RwLock, RefCell, references, and multiple threads.

Also explained in

Compare how 15 books explain deadlock →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.