Deadlocks and lock ordering
Quick answer
Deadlock occurs when participants cannot progress because each waits for resources held by another. Memory-safe Rust can still deadlock or have logic-level races.
Agree on a lock hierarchy
If workers need both locks A and B, acquiring them in a consistent order removes that particular circular-wait pattern. Prefer short critical sections and avoid calling unknown code while holding a lock. try_lock can report contention instead of blocking, but retry policies can still cause starvation or livelock. The examples intentionally avoid hanging programs.
use std::sync::Mutex;fn main() { let a = Mutex::new(0); let b = Mutex::new(0); std::thread::scope(|s| { for _ in 0..2 { s.spawn(|| { let mut first = a.lock().unwrap(); let mut second = b.lock().unwrap(); *first += 1; *second += 1; }); } }); println!("{} {}", *a.lock().unwrap(), *b.lock().unwrap());}Expected stdout (not executed):
2 2Neither worker acquires B before A.
use std::sync::{Mutex, TryLockError};fn main() { let lock = Mutex::new(1); let held = lock.lock().unwrap(); assert!(matches!(lock.try_lock(), Err(TryLockError::WouldBlock))); drop(held); println!("{}", *lock.lock().unwrap());}Expected stdout (not executed):
1A nonblocking probe illustrates a held lock without causing an intentional hang.
Common mistake
Do not hold a lock while joining a worker that needs that lock.
Try it yourself
Draw two workers acquiring A then B versus B then A; identify the possible wait cycle without running it.
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
Deadlocks and lock ordering — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You need to call user-provided code after accessing protected state. How can you reduce lock risk?
Deadlocks and lock ordering — 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 a = Mutex::new(0); let b = Mutex::new(0); std::thread::scope(|s| { for _ in 0..2 { s.spawn(|| { let mut first = a.lock().unwrap(); let mut second = b.lock().unwrap(); *first += 1; *second += 1; }); } }); println!("{} {}", *a.lock().unwrap(), *b.lock().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Deadlocks and lock ordering — 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::{Mutex, TryLockError}; fn main() { let lock = Mutex::new(1); let held = lock.lock().unwrap(); assert!(matches!(lock.try_lock(), Err(TryLockError::WouldBlock))); drop(held); println!("{}", *lock.lock().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.