Double-lock at compile-time?

Does Rust cannot catch the double-lock at compile-time?

Please consider following code:
If I comment std::mem::drop(), then the program occurs deadlock.

use std::sync::Mutex;

fn main() {
    let mutex = Mutex::new(32);
    let mut guard = mutex.lock().unwrap();
    *guard += 1;
    println!("Hello, {}", mutex.lock().unwrap());

No, this won't be picked up at compile time - this is the documented behaviour:

The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).

You can, however, detect this at runtime by using try_lock, which returns a WouldBlock error if the lock is already held somewhere else. If that 'somewhere' is on the same thread, locking would cause a deadlock.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.