Skip to content

[new-lint] if let Some... else with locked mutex #5219

Closed
@DevinR528

Description

@DevinR528

I was working on a project and did something like this

let mutex: Mutex<Option<...>>;
if let Some(thing) = mutex.lock().unwrap() {
    do_thing();
} else {
    mutex.lock();
}

It just sat running and it took me a bit to realize the mutex is locked for the entire scope of the if and else. The suggestion could be something like

warning: locking a `Mutex` twice in the same scope will (fail/freeze/deadlock)
if let Some(thing) = mutex.lock().unwrap() {  <=== lock starts here
    do_thing();                               <=
} else {                                      <=
    mutex.lock();      <= second lock         <= 
}                                             <= lock is droped

or a suggestion to

warning: move lock out of `if let...else`
let locked = mutex.lock().unwrap();
if let Some(thing) = locked {
    do_thing();
} else {
    do_something_else(locked);
}  

I would be happy to start a PR if this sounds good to anyone else!

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsL-correctnessLint: Belongs in the correctness lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions