Skip to content

Using mutex.lock()? risks deadlocks due to PoisonError holding the mutex guard #159930

Open

Description

@maxdexh

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};

fn main() {
    // poison the mutex
    std::panic::catch_unwind(|| {
        let _lock = MUTEX.lock();
        panic!();
    })
    .unwrap_err();

    let _result = wat(); // lock is contained in PoisonError
    _ = wat(); // deadlock
}

static MUTEX: Mutex<i32> = Mutex::new(1);

fn wat() -> Result<(), Box<dyn Error>> {
    *MUTEX.lock()? += 1;
    Ok(())
}

See also zulip.

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.

@rustbot label C-discussion
cc #149359

Activity

  1. added
    needs-triage
    C-discussion
    on Jul 25, 2026
  2. bjorn3 commented on Jul 25, 2026

    @bjorn3
    Member

    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.

  3. maxdexh commented on Jul 25, 2026

    @maxdexh
    Author
  4. maxdexh commented on Jul 25, 2026

    @maxdexh
    MemberAuthor

    Especially the idea of libraries doing something like this in public API scares me.

  5. added
    T-libs
    A-atomic
    and removed
    needs-triage
    on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-atomicC-discussionT-libs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ Proxy