You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Using mutex.lock()? risks deadlocks due to PoisonError holding the mutex guard #159930
A-atomicArea: Atomics, barriers, and sync primitivesC-discussionCategory: Discussion or questions that doesn't represent real issues.T-libsRelevant to the library team, which will review and decide on the PR/issue.
When using methods like Mutex::lock in functions that return a type like Box<dyn Error>, using lock()? can lead to the PoisonError, which contains the lock guard, being held for longer than anticipated.
This is a little bit of a footgun and some basic code search (thanks @bjorn3!) shows that people are actually writing lock()? in their code (note that many of these are File::lock or other unrelated methods).
Also applies to RwLock::write and RwLock::read.
Demo of a deadlock from a PoisonError returned as Box<dyn Error>:
use std::{error::Error, sync::Mutex};fnmain(){// poison the mutex
std::panic::catch_unwind(|| {let _lock = MUTEX.lock();panic!();}).unwrap_err();let _result = wat();// lock is contained in PoisonError
_ = wat();// deadlock}staticMUTEX:Mutex<i32> = Mutex::new(1);fnwat() -> Result<(),Box<dynError>>{*MUTEX.lock()? += 1;Ok(())}
imo there should be a lint against any code that does anything nontrivial to a PoisonError containing a lock guard, but I'm not sure what that would look like.
A-atomicArea: Atomics, barriers, and sync primitivesC-discussionCategory: Discussion or questions that doesn't represent real issues.T-libsRelevant to the library team, which will review and decide on the PR/issue.
Activity
bjorn3 commentedon Jul 25, 2026
A slightly better search: https://github.com/search?q=%22.lock%28%29%3F%22+lang%3Arust+-is%3Afork&type=code It still catches locks on some non-mutex things and when the Into impl discards the PoisonError itself like for example Nannou does.
maxdexh commentedon Jul 25, 2026
maxdexh commentedon Jul 25, 2026
Especially the idea of libraries doing something like this in public API scares me.