When a thread panics while holding Rust's
std::sync::Mutex, the mutex records that it has been "poisoned", and the nextlock()returnsErr(PoisonError). In mid-November the argument flared up again over whether to stabilize a non-poisoningstd::sync::nonpoison::Mutex, and whether a future edition should swap the default. This piece sorts out what lock poisoning protects you from and what it doesn't.
std::sync::nonpoison work (tracking issue rust-lang/rust#134645), wrote that they were stuck on two questions: should the poison and nonpoison implementations be unified, and can poisoning be made effectively free? They re-added I-libs-nominated to get a libs-team decision. In an earlier comment (11-03) they reported an experiment on x86 Linux: packing the poison flag into the futex state word made uncontended lock→mutate→unlock cycles 21% slower at the median.nonpoison soon.HashMap defaulting to SipHash: the safe default is right", "we don't do On Error Resume Next anymore") ran into calls to just switch the default over an edition.So the question on the table isn't the name of a new API. It's a design philosophy: how should the standard library's locks treat panics by default?
The deal with a mutex is that you may temporarily break an invariant while you hold the lock, as long as you restore it before you release. Rain's example:
pub fn process(&self, id: &OperationId, message: Message) {
let mut ops = self.ops.lock().unwrap();
// Invariant: ops tracks every operation
let Some(state) = ops.remove(id) else { return }; // <- temporarily broken here
let next = state.process_message(message); // <- what if this panics?
ops.insert(id.clone(), next); // <- this was supposed to restore it
}
If process_message panics and the stack unwinds, the guard's Drop releases the lock, and ops is left missing an entry. Suppose the panic happened off the main thread, nobody checks the join result, and there's no catch_unwind. Then the corrupted state becomes silently visible to every other thread. Rain shows that a panic in a spawned thread can leave the process exiting with a success code, with nothing but a one-line message to show for it.
Poisoning is the detector that keeps anyone from seeing that half-finished state. The debate splits into three questions:
Mutex<Poison<T>>?).lock().unwrap()) be fixed without dropping poisoning?Drop checks whether the current thread is panicking. If it is, it sets the mutex's poison flag.lock() and try_lock() return Err(PoisonError<MutexGuard<T>>).PoisonError::into_inner() hands you the guard so you can still read the data, and since Rust 1.77 Mutex::clear_poison() clears the flag.