I have bumped into this deadlock scenario while working with Mutex
The struct that contains a field of Mutex
type is as follows:
struct MyStruct {
inner_map: Arc<Mutex<HashMap<i32, Vec<i32>>>>,
}
I have accessed this inner map via lock on Mutex:
impl MyStruct {
fn test_lock(&self, key: &i32) {
let my_option = self.inner_map.lock().unwrap().remove(key);
if let Some(my_vec) = my_option {
for _inner_val in my_vec {
self.inner_map.lock().unwrap();
println!("Passed test_lock1");
}
}
}
}
This is working fine without a deadlock since I removed the value from HashMap
and get the ownership out of the HashMap
Very similar function to test_lock with only difference instead of declaring removed value to my_option
variable used it on the fly if let
call and it is causing deadlock in this case:
impl MyStruct{
// Why this function goes to deadlock since remove gets the ownership of the data?
fn test_lock2(&self, key: &i32) {
if let Some(my_vec) = self.inner_map.lock().unwrap().remove(key) {
for _inner_val in my_vec {
self.inner_map.lock().unwrap();
println!("Passed test_lock2");
}
}
}
}
What is the main reason why declaring a variable changes that kind of behavior?