我有一个大致如下的结构
struct Node {
id: Arc<i32>,
data: Arc<Mutex<i32>>, // Actually not i32, but that is not important for this question.
rx: Receiver<()>,
tx: Sender<()>
}
我使用
Receiver
中的Sender
和mpsc::channel
。我想在多个线程之间共享。我有一个“用户”线程,其中
Node
的用户在Node
上执行一些功能。这将导致一些UDP消息发送到其他计算机,并且该线程将在rx.recv()
上阻止。在后台,我有一个或多个线程在UDP套接字上执行阻止接收调用。当他们接收到一条消息时,便会更新data
结构的Node
字段,并且当后台线程注意到已接收到足够多的消息时,它将使用()
发送tx.send()
,以使用户线程继续其执行。要将
Node
实例共享给另一个线程,我需要执行以下操作:let node: Arc<Node> = ...
let node_for_background_thread = Arc::clone(&node);
let background_thread_handle = thread::spawn(move || {
node_for_background_thread.start_receive_loop();
});
我需要在用户线程和后台线程中都访问
Node
的所有字段(例如id
和data
)。这就是为什么我要在它们之间共享一个Node
实例的原因。但是Receiver
和Sender
都不是Sync
,因此上述内容无法编译。我知道我可以克隆Sender
在每个后台线程中放入一个其中的一个。我看到的一种解决方案是在
rx
中不包括tx
和Node
。但是然后我将丢失封装,因为那时Node
实例的创建者将不得不创建 channel 并生成后台线程。如果可能,我希望将其全部封装在Node
中。上面的代码片段是我可以手动克隆
Sender
的地方。我不需要克隆Receiver
,因为我只有一个线程可以使用它。
最佳答案
当我在这里回答时:https://stackoverflow.com/a/65354846/6070255
You may use std::sync::mpsc::SyncSender from the standard library. The difference is that it implements the
Sync
trait but it will may block if there is no space in the internal buffer while sending a message.For more information:
关于multithreading - 如何跨线程共享包含发送方和接收方字段的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56936956/