Recover Data From A Poisoned Mutex
A panic while holding the lock poisons the Mutex, but PoisonError still hands back the guard data through into_inner for controlled recovery.
Code
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::{Mutex, MutexGuard};
fn crash_while_locked(_guard: MutexGuard<Vec<i32>>) {
// 假设更新进行到一半崩溃:guard 随 unwind 一起析构并给互斥量下毒
panic!("update failed midway");
}
fn main() {
// 默认 hook 会把崩溃信息打到 stderr:静音后输出只剩业务行
std::panic::set_hook(Box::new(|_| {}));
let state = Mutex::new(vec![1, 2, 3]);
let grabbed = state.lock().unwrap();
let outcome = catch_unwind(AssertUnwindSafe(|| crash_while_locked(grabbed)));
println!("caught crash: {}", outcome.is_err());
// 中毒的互斥量:lock 返回 PoisonError,数据本身没有丢
let guard = match state.lock() {
Ok(guard) => guard,
Err(poisoned) => {
println!("poisoned lock, recovering data");
poisoned.into_inner()
}
};
println!("data intact: {:?}", *guard);
}How it works
Structurally, expect the functions crash_while_locked and main and nothing else.
The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
Putting it to use
The main signature reads fn crash_while_locked(_guard: MutexGuard<Vec<i32>>)
Running the file prints labeled results such as caught crash:, poisoned lock, recovering data, data intact: — each operation’s effect is visible in the output.
The entry point wires crash_while_locked together — run it once and the whole demo flows.
Core lines
Err(poisoned) => {
println!("poisoned lock, recovering data");
poisoned.into_inner()
}
fn crash_while_locked(_guard: MutexGuard<Vec<i32>>) {
// 假设更新进行到一半崩溃:guard 随 unwind 一起析构并给互斥量下毒
panic!("update failed midway");
}
let grabbed = state.lock().unwrap();
Interactive Tools for This Topic
FAQ
- What does Recover Data From A Poisoned Mutex print when run?
- Run it as a complete program — the output lines carry labels such as `caught crash:`, `poisoned lock, recovering data`, `data intact:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.