如何像在 Go 中锁定结构一样锁定 Rust 结构?

How to lock a Rust struct the way a struct is locked in Go?

我正在尝试学习如何像在 Go 中那样在 Rust 中使用锁。使用 Go 我可以做类似的事情:

type Info struct {
    sync.RWMutex
    height    uint64 
    verify bool
}

如果我有一些 function/method 信息,我可以这样做:

func (i *Info) DoStuff(myType Data) error {
    i.Lock()
    //do my stuff
}

看来我需要的是sync.RWMutex,所以这是我试过的:

pub struct Info {
    pub lock: sync.RWMutex,
    pub height: u64,
    pub verify: bool,
}

这是正确的做法吗?我将如何从这里开始?

不要用 Go 的方式,用 Rust 的方式。 Mutex and RwLock 是泛型;你把要锁定的数据放在里面里面。稍后,您可以通过 lock guard 访问数据。当锁守卫超出范围时,锁被释放:

use std::sync::RwLock;

#[derive(Debug, Default)]
struct Info {
    data: RwLock<InfoData>,
}

#[derive(Debug, Default)]
struct InfoData {
    height: u64,
    verify: bool,
}

fn main() {
    let info = Info::default();
    let mut data = info.data.write().expect("Lock is poisoned");
    data.height += 42;
}

Go 的解决方案不是最优的,因为没有什么强制你实际使用锁;您可能会忘记获取锁并访问只有在锁定时才能使用的数据。

如果您必须锁定不是数据的东西,您可以只锁定空元组:

use std::sync::RwLock;

#[derive(Debug, Default)]
struct Info {
    lock: RwLock<()>,
    height: u64,
    verify: bool,
}

fn main() {
    let mut info = Info::default();
    let _lock = info.lock.write().expect("Lock is poisoned");
    info.height += 42;
}

另请参阅:

  • What do I use to share an object with many threads and one writer in Rust?
  • When or why should I use a Mutex over an RwLock?