I try lock twice in the mutex, but why there no dead lock in it?
use std::sync::Mutex;
fn main() {
let l = Mutex::<i32>::new(32);
println!("ttt1");
*l.lock().unwrap() = 10;
println!("ttt2");
*l.lock().unwrap() = 11;
println!("ttt3");
}
1 Like
l.lock().unwrap()
, when not assigned to any binding (i.e. not stored in a variable), is a temporary which is dropped at the end of statement, therefore unlocking the lock. If you store the guard, code deadlocks as expected:
use std::sync::Mutex;
fn main() {
let l = Mutex::<i32>::new(32);
println!("ttt1");
let lock1 = l.lock().unwrap();
println!("ttt2");
let lock2 = l.lock().unwrap(); // locks forever
println!("ttt3"); // never runs
}
3 Likes
In case you have to troubleshoot this situation, panic is also a possible outcome.