如何以Go中锁定结构的方式锁定Rust结构? [英] How to lock a Rust struct the way a struct is locked in Go?

查看:95
本文介绍了如何以Go中锁定结构的方式锁定Rust结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何在Rust中使用它们在Go中的工作方式进行锁定.使用Go,我可以做类似的事情:

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
}

似乎我需要的是sync.RWMutex,所以这是我尝试过的:

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?

推荐答案

请不要执行Go方法,请执行Rust方法. Mutex

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

Go解决方案不是最理想的,因为没有什么可以迫使您实际使用锁.您会轻易忘记获取锁定并访问仅在锁定时才使用的数据.

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

另请参阅:

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

这篇关于如何以Go中锁定结构的方式锁定Rust结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆