PoisonError
RustERRORCommonConcurrency

Mutex poisoned

Quick Answer

Call into_inner() on the PoisonError to recover the guard, or restructure to avoid panics inside locks.

What this means

A Mutex or RwLock is poisoned because a thread panicked while holding the lock. The guarded data may be in an inconsistent state.

Why it happens
  1. 1Thread panicked while holding a Mutex lock
  2. 2panic! inside a lock guard's scope

Fix

Recover from poison

Recover from poison
use std::sync::Mutex;
let m = Mutex::new(0i32);
let guard = m.lock().unwrap_or_else(|e| e.into_inner());
println!("value: {}", *guard);

Why this works

into_inner() on PoisonError yields the MutexGuard; you accept responsibility for checking consistency.

Code examples
Poison a mutexrust
let m = std::sync::Arc::new(std::sync::Mutex::new(0));
let m2 = m.clone();
std::thread::spawn(move || { let _g = m2.lock().unwrap(); panic!(); }).join().ok();
let _ = m.lock(); // returns Err(PoisonError)
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors