[英]Write while multiple readers are reading from different threads in Rust
I know I can use RwLock to wait for reading threads to finish reading, although I was wondering if it was possible to write data while the readers were reading non-atomically (I don't really care whether readers get an old copy of the data or a new one, as long as the memory gets updated) Is this possible in safe (or unsafe rust)?我知道我可以使用 RwLock 来等待读取线程完成读取,尽管我想知道是否可以在读者以非原子方式读取时写入数据(我并不关心读者是否获得数据的旧副本或一个新的,只要 memory 得到更新)这可能在安全(或不安全的锈蚀)中吗?
A little more about my specific problem: I have an object that may take a long time to write to but I want to have readers reading from it constantly.关于我的具体问题的更多信息:我有一个 object 可能需要很长时间才能写入,但我想让读者不断地阅读它。
EDIT: More specifically, I have a Cache that holds different objects.编辑:更具体地说,我有一个包含不同对象的缓存。 These objects simply hold a byte (u8) array.
这些对象只保存一个字节 (u8) 数组。 This byte array needs to be read from different threads as well as being written to (the writing parses a large cumbersome struct and converts various fields into the byte array).
这个字节数组需要从不同的线程读取以及写入(写入会解析一个大而繁琐的结构并将各种字段转换为字节数组)。
This is a good use-case of the arc-swap
crate, which allows you to atomically swap oneArc
for another.这是
arc-swap
crate 的一个很好的用例,它允许您以原子方式将一个Arc
交换为另一个。 Every time you wish to create a new version of your data, you create a clone of the data and put the new version in an Arc
, swapping out the old Arc
.每次您希望创建数据的新版本时,您都会创建数据的克隆并将新版本放入
Arc
中,换掉旧的Arc
。 Code that needs to read can get a clone to the Arc
currently in the ArcSwap
, and the old version is destroyed once there are no more handles to the old version.需要读取的代码可以克隆到当前在
ArcSwap
中的Arc
,一旦没有旧版本的句柄,旧版本就会被销毁。
If you need to modify the data from multiple places, you should employ the following pattern using a Mutex
.如果您需要从多个位置修改数据,则应使用
Mutex
采用以下模式。
Mutex
.Mutex
中的更新。Mutex
and put it into the ArcSwap
.Mutex
中的 object 并将其放入ArcSwap
中。 Any code that wishes to read the data will take a clone from the ArcSwap
and never touch the Mutex
.任何希望读取数据的代码都将从
ArcSwap
中克隆,并且永远不会触及Mutex
。 It is important that the mutex is unlocked after swapping the Arc
with the new version.将
Arc
与新版本交换后解锁互斥锁非常重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.