Poisoned locks
A std mutex or write-lock poisons when a thread panics while holding the guard. Later lock calls return Err, because the inner data may be inconsistent.
Detailed Explanation
Mutex::lock returns LockResult<MutexGuard<T>>. Ok is the usual case. Err(PoisonError<Guard>) means some thread panicked inside the critical section. The lock is released — panic runs Drop on the guard — but the value may be half-written: a Vec that was mid-push, a struct with one field updated. Poison is std's way of refusing to pretend that is fine.
unwrap() on the result panics this thread too, which is a reasonable default for programs that treat a poisoned lock as a bug. unwrap_or_else(|e| e.into_inner()) takes the data anyway. You do that when you can repair it, or when you are shutting down and only want to log. lock().unwrap_or_else(|e| e.into_inner()) is a common "I do not care about poison" line; it should be a conscious choice.
RwLock poisons on a panic during a write lock. Read-lock panics do not poison, because readers are not supposed to mutate. parking_lot's mutex does not poison. Tokio's async mutex does not poison. If you switch crates, this behaviour changes.
Poison is not a substitute for not panicking in the critical section. Keep the locked region small. Do not call user callbacks or parse untrusted input while you hold the guard. A panic there is what poisons everyone else.
When you unwrap the lock: a process where a poisoned mutex means "abort, something is deeply wrong". When you recover: a server that must keep serving and has a way to reset the state. When you avoid poison entirely: do not panic under the lock.
Tests that panic! under a lock on purpose will poison the mutex for later tests in the same process if they share the static. Prefer a fresh Mutex per test, or recover with into_inner in a Drop of the test fixture. Shared static mutexes plus should_panic tests are a common source of one flaky test poisoning the next.
Code Examples
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let m = Arc::new(Mutex::new(0i32));
let m2 = Arc::clone(&m);
let _ = thread::spawn(move || {
let _g = m2.lock().unwrap();
panic!("boom");
})
.join();
match m.lock() {
Ok(g) => println!("clean {g}"),
Err(p) => println!("poisoned {}", p.into_inner()), // prints: poisoned 0
}
}Common Gotchas
`unwrap` on a poisoned lock panics a healthy thread
That can take down a whole worker pool. Decide at the crate level what poison means.
Not every mutex crate poisons
`parking_lot` and `tokio::sync::Mutex` do not. Do not copy-paste recovery code that will never run.
Recovered data may be logically invalid
`into_inner` is not a repair. Reset the value or run a consistency check.
Poison is not deadlock
The lock is free. Later threads can lock; they get `Err` instead of hanging.