rust 死锁,当多个方法访问互斥保护结构的不同字段时

q8l4jmvw  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(94)

当多个函数访问互斥保护结构的不同字段时,如何避免死锁,如下所示

use std::sync::Mutex;

#[derive(Default)]
struct InnerData {
    ia: i32,
    ib: i32,
}

#[derive(Default)]
struct OuterData {
    oa: i32,
    ob: Mutex<InnerData>,
}

impl OuterData {
    fn foo(&self) {
        println!("fn foo begin");
        let b_mg = &mut self.ob.lock().unwrap();
        b_mg.ib = 5;
        println!("fn foo end");
    }
}

fn main() {
    let mut outer_data: OuterData = Default::default();
    let b_mg = &mut outer_data.ob.lock().unwrap();
    b_mg.ia = 3;

    if b_mg.ia == 3 {
        outer_data.foo();
    }
}
kq0g1dla

kq0g1dla1#

在这种情况下,您可以将其更改为以下内容:

fn main() {
    let mut outer_data: OuterData = Default::default();
    let mut b_mg = outer_data.ob.lock().unwrap(); // own the MutexGuard to be able to drop it
    b_mg.ia = 3;

    if b_mg.ia == 3 {
        drop(b_mg); // unlock the Mutex before calling foo()
        outer_data.foo();
    }
}

相关问题