0

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?

James Smith
  • 249
  • 1
  • 2
  • 8
  • 8
    This question doesn't show research effort. [Searching the Rust docs for "rwmutex"](https://doc.rust-lang.org/std/sync/struct.Mutex.html?search=rwmutex) points to [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) which has examples. There's also [`RwLock`](https://doc.rust-lang.org/std/sync/struct.RwLock.html) in the same module, also with examples. – Shepmaster Jul 29 '19 at 14:39
  • @Shepmaster I don't understand how those examples relate to structs, sorry. – James Smith Jul 29 '19 at 14:43

1 Answers1

17

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • "If you must lock something that isn't the data", so in this case, what am I really going to lock? In C++, it seems that Mutex is used to lock code. – chenzhongpu Oct 27 '22 at 05:49