gpt4 book ai didi

rust - Arc 是否允许 RwLock 拥有多个写入器?

转载 作者:行者123 更新时间:2023-11-29 08:28:38 25 4
gpt4 key购买 nike

我正在玩这个玩具结构:

pub struct Community {
pub community_contents: RwLock<CommunityContents>,
}

pub struct CommunityContents {
pub friends: RefCell<HashMap<FriendID, FriendData>>,
pub index: RefCell<HashMap<u64, BTreeMap<FriendID, FriendData>>>,
pub authenticated: bool,
pub age: u64,
pub height: u64,
}

我的理论是有一个 Arc RwLock周围的 Community然后我可以有多个作者到 RwLock这些作者可以独立/同时修改 friendsindex CommunityContents 的领域通过Rc<RefCell .

这甚至可能吗?威尔RwLock无论如何,一次都不允许超过一个作者——在这种情况下,我应该删除 RefCells并简化整个结构?

最佳答案

没有。

Arc 不允许它持有的类型发生变化。只能共享不可变引用,Arc 也不异常(exception)。

来自 Arc文档:

Shared references in Rust disallow mutation by default, and Arc is no exception: you cannot generally obtain a mutable reference to something inside an Arc. If you need to mutate through an Arc, use Mutex, RwLock, or one of the Atomic types.

这意味着您必须存储一个具有内部可变性的类型...RwLock 是其中一种类型,并且它的行为相同,无论它是否包装在 Arc 中> 或不。

来自 RwLock文档:

This type of lock allows a number of readers or at most one writer at any point in time.

无论你做什么,都不可能使用安全 Rust 在两个不同的地方获得可变引用,唯一的方法是使用 unsafe {},这无论如何都会导致未定义的行为,类型如 RwLock 确实使用 unsafe{},但是,它们保证写入(可变访问)是独占的,事实上,如果有人正在写入它,它就无法读取,也不能被written to if someone are reading it,这就是这句话的意思。

关于rust - Arc 是否允许 RwLock 拥有多个写入器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com