【发布时间】:2019-06-20 08:18:26
【问题描述】:
我在使用 Mutex 时遇到了这种死锁情况
包含Mutex类型字段的struct如下:
struct MyStruct {
inner_map: Arc<Mutex<HashMap<i32, Vec<i32>>>>,
}
我已经通过互斥锁访问了这个内部地图:
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");
}
}
}
}
由于我从HashMap 中删除了值并从HashMap 中获取了所有权,所以这可以正常工作而没有死锁
与 test_lock 非常相似的函数只有区别,而不是向 my_option 变量声明已删除的值,而是在运行中使用它 if let 调用,在这种情况下会导致死锁强>:
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");
}
}
}
}
声明变量会改变这种行为的主要原因是什么?
【问题讨论】:
-
我怀疑即使在您的第一个非死锁代码中,您也会做一些本质上不安全的事情。没有真实的代码很难说,但是您确定不应该只为测试和条件为真时执行的操作设置一个锁吗?
标签: concurrency rust mutex