Sub topic 9
Mutex poisoning and recovery
This chapter assumes you know Arc<Mutex<T>>, lock guards and Drop, thread::spawn with JoinHandle::join, and Result, unwrap and closures. Here you will learn what poisoning is, why Rust does it, and how to handle it on purpose.
What poisoning is
A Mutex<T> protects data by letting one thread at a time hold its guard. The guard gives you &mut T. Suppose a thread panics while it holds that guard. The panic unwinds the stack and drops the guard, so the lock is released. But the data may be half-updated. A thread that panicked in the middle of a multi-step change may have left the value breaking an invariant that other code relies on.
Rust handles this by marking the mutex as poisoned. Poisoning is a flag on the mutex. The standard library sets it when a MutexGuard is dropped during a panic, and only if the panic started after the guard was acquired. From then on, every call to lock() returns Err(PoisonError<MutexGuard<T>>) instead of Ok(guard).
This is why lock() returns a Result. The Err case is not about contention. It means "a previous holder panicked, so the data may be inconsistent."
What poisoning does and does not do
- It does not stop the lock from working. The mutex still excludes other threads, and the guard is still released.
- It does not stop you from reading the data. The error carries the guard.
- It does not undo the panic's partial changes. Nothing is rolled back.
- It is not memory unsafety. Rust's safety rules still hold. The risk is a logic bug: the data is valid for its type but may be wrong for your program.
A related point: lock().unwrap(), which you have used in earlier examples, turns a poisoned lock into a panic in the current thread. That spreads the failure to every thread that touches the mutex. This is often a reasonable default, because a corrupt shared value is a real problem. It should be a decision, not an accident.
Seeing it happen
The program below poisons a mutex on purpose, then recovers the data.
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);
}It prints recovered value: 0. The panic message from the worker also appears on standard error.
Step by step:
- The worker locks the mutex and panics while
_guardis alive. - Unwinding drops
_guard. Because the thread is panicking, the standard library sets the poison flag. join()returnsErrbecause the thread panicked. This is a separate signal from poisoning. A panic that is caught or that happens outside any lock does not poison anything.is_poisoned()reportstrue.lock()now returnsErr(PoisonError). The closure passed tounwrap_or_elsecallsinto_inner(), which hands back theMutexGuardthat the error was holding.
The guard you get this way is a normal guard. You can read and write through it, and the lock is released when it drops.
The diagram: lifecycle of the poison flag
Your options when you see a PoisonError
You have three reasonable choices. Pick one deliberately for each mutex.
Propagate the failure
lock().unwrap() or lock().expect("state mutex poisoned") panics. Use this when the data would be dangerous to use after a partial update, such as a balance ledger or a structure with cross-field invariants. An expect message makes the later panic easier to trace.
Recover and continue
lock().unwrap_or_else(|e| e.into_inner()) ignores the poison and takes the data. Use this when the data stays valid after any partial update. A counter, a log buffer, or a cache you can rebuild fits here. Even then, think about whether the half-finished operation matters.
Recover, repair, then clear
If you can restore the invariant, do so and clear the flag so the next lock() succeeds normally. Mutex::clear_poison is available in recent Rust releases (stabilized in 1.77). Check your minimum supported Rust version before relying on it.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let m = Arc::new(Mutex::new(vec![1, 2, 3]));
let m2 = Arc::clone(&m);
let _ = thread::spawn(move || {
let mut guard = m2.lock().unwrap();
guard.clear(); // step 1 of a two-step update
panic!("failed before refilling");
})
.join();
let mut guard = match m.lock() {
Ok(guard) => guard,
Err(poisoned) => {
let mut guard = poisoned.into_inner();
*guard = vec![1, 2, 3]; // restore a known-good state
guard
}
};
guard.push(4);
println!("{:?}", *guard);
drop(guard);
m.clear_poison();
println!("poisoned now? {}", m.is_poisoned());
}This prints [1, 2, 3, 4] and then poisoned now? false. Note that the guard is dropped before clear_poison() is called. The repair assigns a known-good value instead of trusting whatever the panicking thread left behind.
try_lock and poisoning
try_lock() does not block. It returns Result<MutexGuard<T>, TryLockError<...>>. TryLockError has two variants: Poisoned (it carries the same recoverable guard) and WouldBlock (another thread holds the lock). Match on both if you use try_lock, and do not treat them as the same failure.
Reading a poisoned mutex by value
When you own the mutex outright, into_inner() on the Mutex itself consumes it and returns LockResult<T>. A poisoned mutex gives Err(PoisonError<T>), and PoisonError::into_inner() gives you the T. get_mut() behaves the same way for &mut Mutex<T>. The same three options apply.
A common mistake: believing poisoning protects you from bad data
Poisoning only fires when a panic passes through a held guard. It does not detect:
- A thread that returns early with an error halfway through an update. The guard drops normally, the flag stays clear, and the data is inconsistent.
- A bug that writes wrong values without panicking.
- Panics that happen after you release the guard.
To keep updates safe regardless, make each critical section either complete or leave the data valid. Build the new value first, then assign it in one step. Chapter-level advice about short critical sections helps here, because less code under the lock means fewer places to fail midway.
Poisoning and other lock types
RwLock poisons too, but only when a writer panics. A panicking reader does not poison it, since readers cannot change the data. Atomics have no poisoning because they have no guards. Be aware that some third-party mutexes, such as the ones in parking_lot, do not poison at all. Switching libraries changes this behavior, so decide it knowingly.
Quick reference
| Situation | Typical choice | Column | Column |
|---|---|---|---|
| Data would be unsafe after a partial update | `lock().expect("...")`, so the panic spreads | ||
| Data is valid after any partial update | `unwrap_or_else(\ | e\ | e.into_inner())` |
| You can rebuild a good state | `into_inner()`, repair, then `clear_poison()` | ||
| Non-blocking attempt | Match `TryLockError::Poisoned` and `WouldBlock` separately |
Exercise
A worker thread locks a Mutex<Vec<u32>>, pushes one value, and then panics after the guard has already been dropped at the end of an inner block. Is the mutex poisoned? What if the panic happens before the inner block ends?
Show answer
No, it is not poisoned in the first case. Poisoning is set only when a guard is dropped while the thread is panicking, and here the guard was released normally before the panic. In the second case the panic unwinds through the live guard, so the guard drops during a panic and the mutex becomes poisoned. Later lock() calls return Err(PoisonError).
Exercise
You have a Mutex<HashMap<String, u64>> used as a metrics cache that can be rebuilt at any time. A panic poisoned it. Write the one-line lock call that continues using the data, and say which invariant you are relying on.
Show answer
let guard = cache.lock().unwrap_or_else(|e| e.into_inner());. This relies on the cache being valid, or at least harmless, after any partial update, since it can be rebuilt. If entries had to stay consistent with each other, you should repair the map or propagate the panic instead.