我如何在 Rust (crossbeam) 中与多个生产者和一个接收者共享字符串消息?

How can I share String messages with multiple producers and a single receiver in Rust (crossbeam)?

我有一个项目,其中多个线程将以字符串格式传输读数,我希望它们由一个处理程序线程使用。

不幸的是,字符串没有实现 Copy/Clone 所以我不能传递我的交叉梁通道的引用所以第二个线程没有得到错误

--> src/main.rs:71:30
|
61 |     let (tx_ws, rx_ws) = unbounded();
|          --------- move occurs because `tx_ws` has type `crossbeam::Sender<node::WebsocketResponse>`, which does not implement the `Copy` trait
...
70 |     let node0_thread = thread::spawn(move || node0::run(Some(&n0_settings), tx_ws.clone()));
|                             ------- value moved into closure here                   --------- variable moved due to use in closure
71 |     let node1_thread = thread::spawn(move || node1::run(Some(&n1_settings), tx_ws.clone()));
|                              ^^^^^^^ value used here after move                  --------- use occurs due to use in closure

你们有什么技巧可以解决这个问题?我知道 String 是非盒装类型,但不确定如何解决它。

是否有其他方法可以通过交叉束通道发送类似字符串的消息?

您正在使用 move 闭包,它会尝试将任何捕获的变量移入,并且您在同一个变量 (tx_ws) 上将其移入不同的闭包中两次。

如果 SenderCopy,这很好,它会被自动复制,但因为它只是 Clone,您需要明确克隆它。您正在尝试调用 clone(),但在闭包内(因此 移动发生之后),为时已晚。

在第 61 行之后,添加如下一行: let tx_ws_clone = tx_ws.clone(); 并将其中一个闭包更改为使用 tx_ws_clone 而不是 tx_ws,事情应该开始起作用了。在闭包内你不需要克隆 tx_ws;你只需要在它被移动之前克隆它:)