Sub topic 10
Deadlock and lock ordering
This chapter assumes you can already use Arc<Mutex<T>>, know that a MutexGuard unlocks when it is dropped, and have read the chapter on keeping critical sections short. Here you will learn how a program that is correct in every other way can still freeze, and how to design against it.
What a deadlock is
A deadlock happens when threads wait for each other forever. Each thread holds a resource that another one needs, and none of them can continue. A Mutex makes this possible because lock() blocks until the lock is free.
Rust's type system prevents data races, but it does not prevent deadlocks. A deadlocked program is memory-safe and compiles cleanly. It simply stops making progress.
The classic case needs two locks and two threads:
- Thread 1 locks
A, then tries to lockB. - Thread 2 locks
B, then tries to lockA. - Thread 1 waits for
B, which Thread 2 holds. Thread 2 waits forA, which Thread 1 holds.
A program that hangs
The sleeps below make the bad interleaving almost certain. Without them the program might work on many runs and hang on one, which is worse.
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let a = Arc::new(Mutex::new(0));
let b = Arc::new(Mutex::new(0));
let (a1, b1) = (Arc::clone(&a), Arc::clone(&b));
let t1 = thread::spawn(move || {
let _ga = a1.lock().unwrap();
thread::sleep(Duration::from_millis(100));
let _gb = b1.lock().unwrap(); // waits for thread 2
println!("thread 1 done");
});
let (a2, b2) = (Arc::clone(&a), Arc::clone(&b));
let t2 = thread::spawn(move || {
let _gb = b2.lock().unwrap();
thread::sleep(Duration::from_millis(100));
let _ga = a2.lock().unwrap(); // waits for thread 1
println!("thread 2 done");
});
t1.join().unwrap();
t2.join().unwrap();
}This program never prints and never exits. The two join calls wait on threads that cannot finish.
A deadlocked process uses no CPU, because its threads are blocked rather than spinning. That is one way to recognize the problem. Another is to attach a debugger and print every thread's backtrace. You will find each thread inside a lock call.
The four conditions
A deadlock needs all four of these conditions at once:
| Condition | In the example |
|---|---|
| Mutual exclusion | A mutex gives access to one thread at a time. |
| Hold and wait | Each thread keeps one lock while asking for another. |
| No preemption | Nothing can take a lock away from a thread. |
| Circular wait | Thread 1 waits on Thread 2, and Thread 2 waits on Thread 1. |
You cannot remove the first or third condition from a standard Mutex. Every practical defense removes the second or the fourth.
Fix 1: a consistent lock ordering
Circular wait is impossible if every thread acquires locks in the same global order. If both threads above lock A before B, then whichever thread gets A first also gets B first. The other thread waits at A and holds nothing, so no cycle can form.
Writing "always A then B" is easy when the locks have fixed names. It is harder when the locks come from data, as in a money transfer between two accounts. Thread 1 may run transfer(x, y) while Thread 2 runs transfer(y, x). The argument order does not give you a global order, but a stable key does. Here that key is an account ID:
use std::sync::Mutex;
use std::thread;
struct Account {
id: u32,
balance: Mutex<i64>,
}
fn transfer(from: &Account, to: &Account, amount: i64) {
if from.id == to.id {
return; // locking the same mutex twice would deadlock
}
let from_first = from.id < to.id;
let (first, second) = if from_first { (from, to) } else { (to, from) };
// Always lock the lower id first.
let mut g1 = first.balance.lock().unwrap();
let mut g2 = second.balance.lock().unwrap();
let (from_bal, to_bal) = if from_first {
(&mut *g1, &mut *g2)
} else {
(&mut *g2, &mut *g1)
};
*from_bal -= amount;
*to_bal += amount;
}
fn main() {
let a = Account { id: 1, balance: Mutex::new(100) };
let b = Account { id: 2, balance: Mutex::new(100) };
thread::scope(|s| {
s.spawn(|| {
for _ in 0..1000 {
transfer(&a, &b, 1);
}
});
s.spawn(|| {
for _ in 0..1000 {
transfer(&b, &a, 1);
}
});
});
println!("{} {}", a.balance.lock().unwrap(), b.balance.lock().unwrap());
}The program prints 100 100. The two threads call transfer with opposite arguments, but both lock account 1 before account 2.
Two details matter:
- The
from.id == to.idcheck is required. Locking oneMutextwice on the same thread either deadlocks or panics. The standard library does not promise which. - The ordering key must be unique and stable. If two different locks can share a key, the order between them is undefined again. A pointer address also works as a key, but an ID is easier to read and debug.
Fix 2: do not hold two locks at once
The simplest ordering rule is to never need an order. Lock one mutex, copy out what you need, drop the guard, then lock the next. This removes hold-and-wait.
It only works when the two steps do not have to be atomic. A transfer that must not be observed half-done, for example, cannot be split. When it can be split, prefer it. Alternatively, put both values inside one Mutex<(A, B)> or one struct. One lock cannot deadlock against itself across threads.
Fix 3: try_lock and back off
Mutex::try_lock returns immediately. It gives Ok(guard) if the lock was free and Err(TryLockError::WouldBlock) if another thread holds it. A thread that cannot get its second lock can release its first lock, wait briefly, and retry. This avoids waiting while holding a lock. The cost is extra code, and a livelock risk if two threads keep backing off in step. Use it when you cannot establish an ordering, such as when the locks come from plugin code.
Self-deadlock from temporaries
A thread can deadlock with only one other lock: its own. The usual cause is a guard that lives longer than it looks. A temporary guard in the scrutinee of if let or match lives until the end of the whole statement.
use std::sync::Mutex;
fn main() {
let queue = Mutex::new(vec![1, 2, 3]);
// Deadlocks: the guard from the first lock() lives through the body,
// so the second lock() waits for the thread's own guard.
//
// if let Some(item) = queue.lock().unwrap().pop() {
// queue.lock().unwrap().push(item + 10);
// }
let popped = queue.lock().unwrap().pop(); // guard dropped at the semicolon
if let Some(item) = popped {
queue.lock().unwrap().push(item + 10);
}
println!("{:?}", queue.lock().unwrap());
}The program prints [1, 2, 13]. Moving the lock() into its own let statement ends the guard's life at the semicolon.
Related ways to hang
Not every hang comes from two mutexes. These look the same from outside:
- Waiting on a join while holding a lock. Thread 1 holds a guard and calls
handle.join(). The joined thread needs that lock to finish. - Blocking on a channel while holding a lock. A thread calls
recv()with a guard held. The sender needs the same lock before it can send. RwLockupgrades. A thread holds a read guard and then asks for a write lock on the sameRwLock. The write request waits for all readers, including the thread itself.
The rule behind all of these is the same: avoid blocking operations while you hold a guard.
Choosing a defense
| Situation | Approach |
|---|---|
| Locks have fixed roles | Document one global order and follow it. |
| Locks come from runtime data | Order by a stable unique key, as in `transfer`. |
| Steps do not need to be atomic | Lock one mutex at a time. |
| Related data is always used together | Put it under one mutex. |
| Order cannot be known | Use `try_lock` with back-off. |
Testing for deadlocks
A deadlock depends on timing, so tests may pass for months. Two habits help. First, write down the lock order next to the data structure and check new code against it in review. Second, stress-test with many threads and a timeout on the whole test. A hung test then fails with a clear message instead of freezing CI. Tools that model thread interleavings, such as the loom crate, can explore orderings systematically if your code is critical enough to need them.
Exercise
Thread 1 locks mutex X and then mutex Y. Thread 2 locks mutex Y and then mutex X. Name the deadlock condition that a consistent lock ordering removes, and say what you would change in the code.
Show answer
A consistent ordering removes circular wait. Pick one order, for example X before Y, and make both threads lock X first and Y second. Thread 2 then waits at X while holding nothing, so Thread 1 can always get Y and finish.
Exercise
This code hangs: if let Some(x) = list.lock().unwrap().first().copied() { list.lock().unwrap().push(x); }. Why, and how do you fix it?
Show answer
The guard returned by the first lock() is a temporary that lives until the end of the whole if let statement, including its body. The second lock() waits for a lock the same thread already holds. Fix it by moving the first lock into a separate statement, let first = list.lock().unwrap().first().copied();, so the guard is dropped at the semicolon, and then using if let Some(x) = first.