Diagnose a service that hangs under load and then reports poisoned-mutex errors
Stock lives in Vec<Mutex<Stock>>. transfer_stock(from, to, qty) locks stock[from], then stock[to], subtracts qty and panics with insufficient stock when the source is too small. Under load two workers hang, and later requests fail on a poisoned lock. Name the cause of each symptom and a fix for each that keeps a transfer atomic.
thread dump (trimmed to our frames):
worker-1 Mutex::lock <- transfer_stock (orders.rs:41) holds stock[12]
worker-3 Mutex::lock <- transfer_stock (orders.rs:41) holds stock[7]
log:
10:14:02 worker-1 locked stock[12], waiting for stock[7]
10:14:02 worker-3 locked stock[7], waiting for stock[12]
10:14:07 worker-2 panicked at src/orders.rs:44:9: insufficient stock: have 3, need 5
10:14:09 api: stock lock failed: poisoned lock: another task failed insideDiagnose the cause.
Workers 1 and 3 each hold one stock lock and wait for the other, since transfer_stock locks in argument order. Separately, worker 2 panicked while holding a guard and poisoned that mutex. Lock pairs by index; check stock before changing it.
- Reading the two symptoms as one bug, though the hang is a lock-order cycle and the poison comes from a separate panic
- Silencing poisoning with
into_inner()everywhere, which hides half-updated data instead of fixing the panic that caused it - Expecting
try_lockto skip the poison check, though it returnsTryLockError::Poisonedjust aslockreturns an error
- How does the lock crate
parking_lothelp find such cycles with its deadlock detection feature? - What happens in your fix when
fromandtoname the same item?
The dump shows two threads in Mutex::lock, each holding what the other waits for: worker-1 holds stock[12] and waits for stock[7], worker-3 the reverse. It is the classic cycle: transfers 12→7 and 7→12 lock the items in argument order. The poisoning is a separate story: worker-2 panicked in transfer_stock while holding a guard, and that item's mutex stayed poisoned, so api gets poisoned lock. The compiler catches neither: safe Rust rules out data races, not deadlocks or logic errors.
Both fixes live in one function: pairs are always locked in increasing index order, and the stock is checked before anything changes, so a panic cannot leave a transfer half done.
use std::sync::{Mutex, MutexGuard};
use std::thread;
struct Stock {
qty: u32,
}
// Every caller locks the lower index first, so no two threads wait on each other.
fn lock_pair(
stock: &[Mutex<Stock>],
a: usize,
b: usize,
) -> (MutexGuard<'_, Stock>, MutexGuard<'_, Stock>) {
if a < b {
let ga = stock[a].lock().unwrap();
(ga, stock[b].lock().unwrap())
} else {
let gb = stock[b].lock().unwrap();
(stock[a].lock().unwrap(), gb)
}
}
fn transfer_stock(stock: &[Mutex<Stock>], from: usize, to: usize, qty: u32) -> Result<(), String> {
if from == to {
return Ok(()); // locking one mutex twice would hang
}
let (mut src, mut dst) = lock_pair(stock, from, to);
if src.qty < qty {
// check before changing anything: no panic, no half-done update
return Err(format!("insufficient stock: have {}, need {qty}", src.qty));
}
src.qty -= qty;
dst.qty += qty;
Ok(())
}
fn main() {
let stock: Vec<Mutex<Stock>> = (0..3).map(|_| Mutex::new(Stock { qty: 10 })).collect();
thread::scope(|s| {
for i in 0..100 {
let stock = &stock;
s.spawn(move || {
let _ = transfer_stock(stock, i % 3, (i + 1) % 3, 1);
let _ = transfer_stock(stock, (i + 1) % 3, i % 3, 1);
});
}
});
let total: u32 = stock.iter().map(|m| m.lock().unwrap().qty).sum();
println!("{total}"); // 30
println!("{}", transfer_stock(&stock, 0, 1, 99).is_err()); // true
}A mutex already poisoned before the fix ships can be recovered: into_inner() on the PoisonError hands back the guard, the data is checked, then clear_poison() is called. To catch such cycles earlier, keep the lock-order logging, take a thread dump (gdb, thread apply all bt) when the service hangs, or turn on the parking_lot crate's deadlock detection in a test build.