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

Jam*_*ith -3 mutex locking rust

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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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,
}
Run Code Online (Sandbox Code Playgroud)

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

She*_*ter 9

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

See also:


归档时间:

查看次数:

104 次

最近记录:

6 年,3 月 前