In defense of lock poisoning in Rust

https://sunshowers.io/posts/on-poisoning/

Comments

bheadmasterDec 3, 2025, 8:22 AM
As a Go programmer, I find it quite puzzling that Rust didn't handle panic edge cases as well as Go did with defer keyword. Defer executes at the end of a function, regardless of whether it returned or panic'd, so you can write safe mutex code just by doing something like:

    mutex.Lock()
    defer mutex.Unlock()
And if you need to unlock the mutex in one of multiple places, you can wrap it into a sync.Once.

There must be a reason Rust doesn't do something similar...

zidelDec 3, 2025, 1:02 PM
Rust handles this by automatically unlocking when the MutexGuard returned by lock() is dropped. The issue here is not that the mutex remains locked, but rather that the data protected by the mutex might be inconsistent (and the mutex unlocked) after a panic.
bheadmasterDec 3, 2025, 1:34 PM
Ah, so my understanding of the problem was wrong.

Thanks for the clarification.

wahernDec 3, 2025, 10:18 AM
It does do something similar... and more. IIUC, when unwinding on panic Rust does unlock the mutex, but it also "poisons" it so that a subsequent attempt to lock will return an error. This is because on panic all the code protected by the mutex didn't get to run to completion, possibly leaving an inconsistent state. A poisoned mutex can be reset, though.
IshKebabDec 4, 2025, 5:03 PM
I don't think editions can change library APIs. It's a good idea though.
sunshowersDec 4, 2025, 6:41 PM
Editions can definitely be made to alter standard library APIs in principle, thought the machinery for that probably needs to be developed a bit. But that's why I qualified my proposal with "if a breaking change is going to happen".