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

前提是你 提交于 2020-01-03 07:17:46

问题


I'm trying to learn how to do locks in Rust the way they work in Go. With Go I can do something like:

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

If I have some function/method acting on info I can do this:

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

It seems like what I need is the sync.RWMutex, so this is what I have tried:

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

Is this the correct approach? How would I proceed from here?


回答1:


Don't do it the Go way, do it the Rust way. Mutex and RwLock are generic types; you put the data to be locked inside of them. Later, you access the data through the lock guard. When the lock guard goes out of scope, the lock is released:

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;
}

The Go solution is suboptimal as nothing forces you to actually use the lock; you can trivially forget to acquire the lock and access data that should only be used when locked.

If you must lock something that isn't the data, you can just lock the empty tuple:

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;
}

See also:

  • 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?


来源:https://stackoverflow.com/questions/57256035/how-to-lock-a-rust-struct-the-way-a-struct-is-locked-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!