In one line: Rust's
std::sync::Mutexuses a poison flag to tell later lockers that "a thread panicked while holding this lock." The community is now split over whether the next edition should switch to "non-poisoning by default, opt in with aPoison<T>wrapper" or move toward "lock()panics automatically on poison." Whichever way it goes, it is a good prompt to redesign what happens in your own code when a critical section gets interrupted halfway.
std::sync::nonpoison tracking issue #134645, mitsuhiko and the assignee connortsui20 each posted prototypes that share the implementation between poisoning and non-poisoning locks via an internal policy type. As of 10-13 the libs team had said it would likely not stabilize the API as-is and wanted the implementations unified first, so this is moving right now.std::sync::Mutex for the nonpoison version in Edition 2027, was updated on 11-28 with links to both blog posts. Nothing is decided yet (it is labeled maybe-future-edition).In short, a debate about changing a default that has held for over a decade since Rust 1.0, and that touches the character of the language, is hot this week. Both camps bring real-world examples, which makes it excellent teaching material.
Critical sections (the code that runs while a lock is held) tend to be written on the implicit assumption that once entered, they run to completion. Simplifying sunshowers' example:
use std::{collections::HashMap, sync::Mutex};
struct Operations {
ops: Mutex<HashMap<OperationId, OperationState>>,
}
impl Operations {
pub fn process(&self, id: &OperationId, msg: Message) {
let mut ops = self.ops.lock().unwrap();
let Some(state) = ops.remove(id) else { return }; // (1) take it out (invariant broken)
let next = state.process_message(msg); // (2) what if this panics?
ops.insert(id.clone(), next); // (3) put it back (invariant restored)
}
}
If (2) panics, and
panic = "unwind" (the default),catch_unwind, and the JoinHandle::join result is ignored (common with thread pools, request handlers and tokio tasks),then other threads can take the lock while the in-flight operation has vanished from the map. The data is well-typed but logically corrupt. Poisoning exists to detect exactly this.
Poisoning, however, has problems of its own:
lock().unwrap() panics. Thread pools and the like keep the process alive, so you get a service that is up but can do nothing.PoisonError holds the guard: to ignore the poison and carry on you have to extract the guard from the error, so the lock stays held for as long as the error lives.?, cancellation at an async .await point, or the same kind of corruption in a RefCell."Silently expose broken state" versus "stop everything after it, including work that would have been fine." That is the core of the debate.