Sub topic 10
Deadlock and lock ordering
This chapter assumes you know Arc<Mutex<T>>, how a MutexGuard releases its lock when dropped, and how to spawn and join threads.
What a deadlock is
A deadlock happens when threads wait for each other forever. Thread 1 holds lock A and waits for lock B. Thread 2 holds lock B and waits for lock A. Neither can continue, and neither will release what it holds.
Rust's type system prevents data races. It does not prevent deadlocks, and safe code can hang this way.
A program that hangs
The sleeps make the bad timing reliable. This program never finishes.
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 t2
});
let t2 = thread::spawn(move || {
let _gb = b.lock().unwrap();
thread::sleep(Duration::from_millis(100));
let _ga = a.lock().unwrap(); // waits for t1
});
t1.join().unwrap();
t2.join().unwrap();
}The cause is that the two threads acquire the locks in opposite orders.
The fix: one global lock order
Pick a fixed order for all locks and have every thread follow it. If every thread locks A before B, no thread can hold B while waiting for A, so a cycle cannot form.
When the order is not obvious, derive it from something stable such as an ID. This bank-transfer example always locks the account with the lower ID first, regardless of transfer direction.
use std::sync::{Arc, 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
}
if from.id < to.id {
let mut f = from.balance.lock().unwrap();
let mut t = to.balance.lock().unwrap();
*f -= amount;
*t += amount;
} else {
let mut t = to.balance.lock().unwrap();
let mut f = from.balance.lock().unwrap();
*f -= amount;
*t += amount;
}
}
fn main() {
let a = Arc::new(Account { id: 1, balance: Mutex::new(1000) });
let b = Arc::new(Account { id: 2, balance: Mutex::new(1000) });
let (a1, b1) = (Arc::clone(&a), Arc::clone(&b));
let t1 = thread::spawn(move || {
for _ in 0..1000 {
transfer(&a1, &b1, 1);
}
});
let (a2, b2) = (Arc::clone(&a), Arc::clone(&b));
let t2 = thread::spawn(move || {
for _ in 0..1000 {
transfer(&b2, &a2, 1);
}
});
t1.join().unwrap();
t2.join().unwrap();
println!("{} {}", a.balance.lock().unwrap(), b.balance.lock().unwrap());
}The two threads transfer in opposite directions, but both lock account 1 first. The program finishes and prints 1000 1000.
Other ways to deadlock
Lock ordering is not the only cause.
- Relocking in the same thread. Calling
lock()on a mutex whose guard you already hold may deadlock or panic. The standard library does not specify which. - Waiting while holding a guard. Calling
join()on a thread that needs your lock, or blocking on a channel receive that depends on it, creates the same cycle. - Calling unknown code under a lock. A callback might take another lock in an order you did not plan for.
Reducing the risk
- Hold as few locks at once as you can. Keep critical sections short, as in the previous chapter.
- If two values always change together, put both in one
Mutexas a struct or tuple. One lock cannot deadlock against itself across threads. - Document the lock order next to the types that own the locks.
- Use
try_lock()where giving up is acceptable. It returns an error instead of blocking, so the thread can release what it holds and retry.
Exercise
Thread 1 locks x and then y. Thread 2 locks y and then x. Name two different changes that remove the deadlock risk.
Show answer
Make both threads lock in the same order, for example x then y. Alternatively, combine x and y into a single value behind one Mutex, so only one lock exists.