Skip to content

clippy::mut_mutex_lock after an immutable reference is held #9854

Closed
@Will-Low

Description

@Will-Low

Summary

When an immutable reference is held, Clippy still suggests using get_mut() instead of lock() for Mutexes, even though this does not work, since it cannot borrow a mutable reference at the same time as an immutable reference.

Lint Name

mut_mutex_lock

Reproducer

I tried this code:

use std::sync::Mutex;
use std::thread;

fn main() {
    let val = Box::leak(Box::new(Mutex::new("my value".to_string())));
    new_thread(val);
    val.lock().unwrap().push('z');
}

fn new_thread(val: &'static Mutex<String>) {
    thread::spawn(move || loop {
        println!("{}", val.lock().unwrap());
    });
}

I saw this happen:

    Checking playground v0.0.1 (/playground)
warning: calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference
 --> src/main.rs:7:9
  |
7 |     val.lock().unwrap().push('z');
  |         ^^^^ help: change this to: `get_mut`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#mut_mutex_lock
  = note: `#[warn(clippy::mut_mutex_lock)]` on by default

warning: `playground` (bin "playground") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.92s

When following Clippy's suggestion:

Checking playground v0.0.1 (/playground)
error[[E0502]](https://doc.rust-lang.org/stable/error-index.html#E0502): cannot borrow `*val` as mutable because it is also borrowed as immutable
 --> src/main.rs:7:5
  |
6 |     new_thread(val);
  |     ---------------
  |     |          |
  |     |          immutable borrow occurs here
  |     argument requires that `*val` is borrowed for `'static`
7 |     val.get_mut().unwrap().push('z');
  |     ^^^^^^^^^^^^^ mutable borrow occurs here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` due to previous error

I expected to see this happen:
No lint suggested

Version

rustc 1.65.0 (897e37553 2022-11-02)
binary: rustc
commit-hash: 897e37553bba8b42751c67658967889d11ecd120
commit-date: 2022-11-02
host: aarch64-apple-darwin
release: 1.65.0
LLVM version: 15.0.0

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions