Sub topic 9
Mutex poisoning and recovery
This chapter assumes you know Arc<Mutex<T>>, lock guards and how thread::spawn and JoinHandle::join report panics. Here you will see what happens when a thread panics while it holds a lock, and how to respond on purpose.
What poisoning is
A Mutex protects data that must stay consistent. Suppose a thread locks the mutex and starts a multi-step update, then panics halfway. The guard is dropped during unwinding, so the lock is released. But the data may now be in a half-updated state.
Rust handles this by marking the mutex as poisoned. A poisoned mutex still works, but every later call to lock() returns an Err instead of an Ok guard. The error forces the next thread to decide what to do about data that might be inconsistent.
Detecting poison
lock() returns Result<MutexGuard<T>, PoisonError<MutexGuard<T>>>. This is why you write .unwrap() on it so often. With a poisoned mutex, that unwrap() panics too, and the failure spreads to every thread that touches the lock.
You can also check without locking, using is_poisoned().
Recovering deliberately
A PoisonError still contains the guard. Calling into_inner() on the error gives you the guard, so you can use the data anyway. The example below poisons a mutex on purpose and then recovers it.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let m = Arc::new(Mutex::new(0));
let m2 = Arc::clone(&m);
let result = thread::spawn(move || {
let _guard = m2.lock().unwrap();
panic!("worker failed while holding the lock");
})
.join();
assert!(result.is_err());
assert!(m.is_poisoned());
let guard = m.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
println!("recovered value: {}", *guard);
}The program prints recovered value: 0. The worker panics with the lock held, so join() returns Err and is_poisoned() is true. The unwrap_or_else call turns the error into a usable guard.
The panic message from the worker also appears on stderr. That is expected.
Choosing a policy
Recovering is not always right. Pick a policy based on what the data means.
| Situation | Reasonable response |
|---|---|
| Each update is a single step, such as pushing to a `Vec` | Recover with `into_inner()`. The data cannot be half-written. |
| Updates span several fields that must agree | Propagate the failure with `unwrap()` or return an error. |
| You can rebuild or validate the data | Recover, then check or reset the contents. |
Since Rust 1.77, Mutex::clear_poison() resets the poison flag. Call it only after you have repaired or validated the data. Otherwise every later lock() keeps returning Err, even after you have handled the problem.
Reducing the risk
- Keep critical sections short. A shorter section has fewer places to panic, which leaves less chance to poison the lock.
- Avoid
unwrap(), indexing and arithmetic that can overflow while the guard is alive, when you can do that work before locking. - Finish an update fully, or make it a single step, so that a panic cannot leave the data half-changed.
Exercise
A worker thread panics while holding a MutexGuard. A second thread then runs let g = m.lock().unwrap();. What happens, and how can the second thread get the data without panicking?
Show answer
The mutex is poisoned, so lock() returns Err(PoisonError) and unwrap() panics in the second thread. To avoid that, the second thread can use m.lock().unwrap_or_else(|e| e.into_inner()), which returns the guard inside the error. It should do this only if the data is safe to use after the panic.
Exercise
Why is recovering from poison fine for a Mutex<Vec<i32>> where threads only call push, but risky for a mutex guarding a bank account with separate balance and history fields?
Show answer
A single push finishes or does not happen, so the vector stays valid. The account update changes two fields. A panic between the two writes leaves balance and history disagreeing, so continuing without checking could produce wrong results.