error-concept

Mutex poison recovery: repair before clearing

A panic while a guard is held can mark a mutex as poisoned. Poisoning is advisory and not a soundness guarantee. This fixture uses unwinding and repairs a deliberately invalid value before clearing the flag. The panic is caught, but its default hook can still emit a diagnostic. Expected stdout (not executed): true 10 Common mistake: Ignoring poison without repairing or checking the protected invariant. The temporary silent hook is a fixture-only choice to make stderr deterministic. It is restored immediately; do not suppress production panic reporting. Requires panic=unwind.

Formal Syntax & Structure

rust syntaxrust
PoisonError::into_inner(); Mutex::clear_poison()

Working Example

Example Snippetrust
fn main() {    use std::sync::Mutex;    let m = Mutex::new(10);    let old_hook = std::panic::take_hook();    std::panic::set_hook(Box::new(|_| {}));    let result = std::panic::catch_unwind(|| { let mut g = m.lock().unwrap(); *g = -1; panic!("synthetic failure"); });    std::panic::set_hook(old_hook);    println!("{}", result.is_err() && m.is_poisoned());    { let mut g = m.lock().unwrap_err().into_inner(); *g = 10; m.clear_poison(); }    println!("{}", *m.lock().unwrap());}
Rust Reference