In Rust, what happens to a `std::sync::Mutex` when a thread panics while holding its guard, and how can other threads still recover the data?
answer
- panic during the critical section
- unwinding drops the guard
- Err still carries the guard
- PoisonError::into_inner
- clear_poison resets the flag
basics
~20 sUnwinding drops the guard, which unlocks the mutex but marks it poisoned, so later lock() calls return Err(PoisonError). The error still holds the guard: into_inner() recovers it, and clear_poison(), stable since Rust 1.77, resets the flag.
solid answer
~40 sWhen the holder panics, unwinding runs the `MutexGuard`'s `Drop`, which releases the lock and sets the poison flag. From then on `lock()` returns `Err(PoisonError<MutexGuard<T>>)` and `try_lock()` returns `TryLockError::Poisoned`, while `into_inner` and `get_mut` on the mutex return `Err` too. The lock is acquired anyway: `PoisonError::into_inner()` hands back the guard, so you can inspect or repair the data. The flag stays set until `Mutex::clear_poison()`, stable since Rust 1.77. Poisoning is advisory and best-effort: an `RwLock` is poisoned only by a writer's panic, a `panic = "abort"` build never gets that far, and unsafe code must not depend on it. Most code calls `lock().unwrap()` on purpose so the failure spreads instead of being read as valid state.
code
rust · 28 linesuse std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let limiter = Arc::new(Mutex::new(HashMap::from([("client-1".to_string(), 0u32)])));
let l2 = Arc::clone(&limiter);
let joined = thread::spawn(move || {
let mut map = l2.lock().unwrap();
*map.get_mut("client-1").unwrap() += 1;
panic!("bug while holding the guard");
})
.join();
println!("join is_err = {}, poisoned = {}", joined.is_err(), limiter.is_poisoned());
let map = match limiter.lock() {
Ok(guard) => guard,
Err(poisoned) => {
println!("lock() returned Err(PoisonError)");
poisoned.into_inner() // the guard, lock held
}
};
println!("value written before the panic: {:?}", map.get("client-1"));
drop(map);
limiter.clear_poison(); // stable since Rust 1.77
println!("poisoned after clear_poison = {}", limiter.is_poisoned());
}go deeper
Recall that lock() returns a Result because of poisoning, and that unwrap() on it panics when another thread died while holding the lock.
Explain that unwinding releases the lock and sets the flag, that the Err still contains a guard, and how into_inner and clear_poison work.
Choose per lock whether to propagate, repair and clear, or ignore poison, and know where detection is best-effort: RwLock readers, panic = abort and double panics.
Weigh std's poisoning against parking_lot's absence of it as a team default, considering how the service should behave after a bug corrupts shared state.
## What poisoning is std's lock types in `std::sync` implement a strategy called **poisoning**. A `Mutex` becomes poisoned when it recognises that the thread holding its guard panicked. The reasoning is that a panic in the middle of a critical section may have left the protected data half-updated — a rate limiter's count incremented but its window timestamp not yet reset, say — so other threads should not silently carry on as if nothing happened. Mechanically, a panic unwinds the thread's stack and runs destructors, including the guard's `Drop`. That drop does two things: it records that the thread was panicking, which sets the poison flag, and it **unlocks** the mutex. Other threads are therefore never stuck waiting forever on a dead thread; they get the lock, plus a warning. ## What other threads see Every later `lock()` and `try_lock()` returns an error until the flag is cleared: - `lock()` returns `LockResult<MutexGuard<'_, T>>`, which is `Err(PoisonError<MutexGuard<'_, T>>)` on a poisoned mutex. The lock **is** acquired; the guard sits inside the error. - `try_lock()` returns `Err(TryLockError::Poisoned(..))` instead. - `Mutex::into_inner(self)` and `Mutex::get_mut(&mut self)` also return `LockResult`, carrying the data in the error. - `Mutex::is_poisoned()` reports the flag without locking. The common `lock().unwrap()` turns the poison into a panic in the next thread too. That is deliberate: it propagates the failure instead of letting code observe a broken invariant. ## Recovering the data Poisoning is **advisory**. You can always get at the data: 1. `PoisonError::into_inner()` returns the guard that `lock()` would have returned; `get_ref()` and `get_mut()` borrow it without consuming the error. 2. Inspect or repair the value through that guard — recompute the counts, or reset the client's entry to a known-good state. 3. Call `Mutex::clear_poison()` (stable since **Rust 1.77**) to mark the mutex healthy again. Without it, the mutex stays poisoned and every later caller still gets `Err`, even after you recovered once. `clear_poison` takes `&self`, so it can be called while another reference exists; the std example calls it from inside `unwrap_or_else` while holding the recovered guard. ## Limits of the mechanism | Situation | Effect on poisoning | |---|---| | Panic while holding a `Mutex` guard, `panic = "unwind"` | mutex poisoned, lock released | | Panic while holding an `RwLock` **write** guard | lock poisoned | | Panic while holding an `RwLock` **read** guard | not poisoned | | Build with `panic = "abort"` | the process ends, so nothing remains to observe | | Locked while a panic is already underway (in a `Drop` or panic hook), then a second panic | can leave the mutex unpoisoned | The std docs are explicit that panic detection is "not ideal": a lock taken while a panic is already underway, guards moved across panic contexts, and foreign exceptions can all skip poisoning. For that reason **unsafe code must not rely on poisoning for soundness** — it is a diagnostic for safe code, not a guarantee. ## Choosing a policy - **`lock().unwrap()` or `expect("limiter mutex poisoned")`** — the default in most services: a poisoned lock means a bug, and failing loudly is safer than serving decisions from damaged state. - **Recover with `into_inner()` and `clear_poison()`** — right when the data can be validated or rebuilt cheaply, such as a cache or a counter table that can be reset. - **Ignore it with `unwrap_or_else(PoisonError::into_inner)`** — acceptable only when every update is a single step that cannot leave the value inconsistent. For a rate limiter the trade-off is concrete. A poisoned counter table is cheap to rebuild: resetting a client's entry at worst gives that client a fresh window, so repairing and clearing is reasonable. State such as account balances, where a half-applied update is costly, should fail loudly instead. The panic itself also surfaces elsewhere: the panicking thread's `JoinHandle::join` returns `Err` with the panic payload, which is covered with spawning threads. `parking_lot::Mutex` does not poison at all: its `lock()` returns the guard directly and a panic just releases the lock. std is also developing non-poisoning lock types in `std::sync::nonpoison`, which is unstable in Rust 1.99 and not usable on stable.
- Does a panic inside a thread that holds an `RwLock` read guard poison it?No. std documents that an `RwLock` is poisoned only when a panic happens while it is locked exclusively, in write mode. A reader cannot have modified the data through a shared guard, so its panic leaves the lock usable and later `read()` and `write()` calls return `Ok`.
- If you recover with `PoisonError::into_inner()` but never call `clear_poison()`, what does the next `lock()` return?`Err(PoisonError)` again. Recovering a guard does not change the mutex's flag; it stays poisoned until `Mutex::clear_poison()` runs. Code that recovers once and then calls `lock().unwrap()` elsewhere will still panic there, so a recovery path should repair the data and clear the flag together.
- Why can't unsafe code use poisoning to guarantee that nobody sees a half-written value?Because std only promises best-effort detection. Its docs list cases where poisoning is skipped: locking while a panic is already underway, as in a `Drop` or panic hook, moving guards across panic contexts, and foreign exceptions. A use-after-free that relies on the flag being set would still be reachable, so soundness must come from the code's own invariants.
- A panic while holding the guard leaves the mutex locked forever
- Once a Mutex is poisoned its data can never be read again
- PoisonError::into_inner also clears the poisoned flag on the mutex
- Any panic in a reader poisons a std RwLock
- Poisoning is reliable enough for unsafe code to depend on it
Assumes Rust 1.99; Mutex::clear_poison and RwLock::clear_poison are stable since 1.77, and std::sync::nonpoison is still unstable.