如何在Rust中在不使用互斥锁的情况下在线程之间传输最新状态

huangapple go评论76阅读模式
英文:

How to transfer latest state between threads in rust without using a mutex

问题

我正在进行一个Rust项目,在这个项目中,我有两个不同的线程,分别用于特定的目的。一个是实时线程,直接与硬件部件进行交互并维护严格的时间要求,而另一个是Web服务器线程,提供API以查询所述硬件的当前状态。

我需要一种机制,使Web服务器线程能够从实时线程获取硬件的最新状态。这里的挑战在于避免使用互斥锁,因为实时线程不能承受等待互斥锁而被阻塞的情况。

以下是我考虑过的一些解决方案及其相应的挑战:

  1. rwlock:但写入线程(实时线程)需要等待,如果有任何读取器锁定它。
  2. 双缓冲:执行交换的线程需要对整个结构体的可变引用,这会引发借用检查器问题。
  3. mpsc Channel:如果没有进行Web请求,通道可能会迅速填满,导致内存浪费。
英文:

I am working on a Rust project where I have two distinct threads that serve specific purposes. One is a real-time thread which interfaces directly with a piece of hardware and maintains strict timing requirements, while the other is a web server thread that provides an API for querying the current state of said hardware.

I need a mechanism through which the web server thread can acquire the most recent state of the hardware from the real-time thread. The challenge here is to avoid the use of mutexes, as the real-time thread cannot afford to be blocked waiting for the mutex.

Here are a few solutions I have considered and their corresponding challenges:

  1. rwlock: But the writer thread (real-time thread) would need to wait if any reader has a lock on it.
  2. Double Buffering: The thread that does the swap needs a mutable reference to the entire struct, which causes borrow checker problems.
  3. mpsc Channel: If there are no web requests being made, the channel could fill up quickly, leading to wasted memory.

答案1

得分: 2

你可以使用 arc-swap crate,它提供了 ArcSwap 类型(以及相关类型):这是一个可以在无锁的方式下进行替换和加载的 Arc

英文:

You can use the arc-swap crate, that provides the ArcSwap type (and related types): an Arc that can be replaced and loaded in a lock-free fashion.

答案2

得分: 1

我最终使用了大小为1的 ring channel,它使用了 crossbeaml 下的 AtomicCell<Option<Box<T>>>

实时线程可以向通道中的 send(),这是原子且无锁的。然后,Web 线程可以从通道中的 recv(),或者如果通道中没有内容,可以继续使用上次读取的值。

英文:

I ended up using a ring channel with size 1, which uses a AtomicCell<Option<Box<T>>> from crossbeaml underneath.

The real-time thread can send() into the channel, which is atomic and lock-free. Then the web thread can recv() from the channel, or if there's nothing in the channel, continue using the last read value.

huangapple
  • 本文由 发表于 2023年8月4日 01:32:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定