我有一些涉及使用嵌套循环的多线程代码,其中内部循环并行运行。每个线程之间的“共享”是一个Sender
将返回结果的。值得注意的是,因此Sender
克隆Send
它并使用人造丝发送它应该没有问题for_each_with()
。但是,编译此代码:
use std::sync::mpsc::channel;
use rayon::prelude::*;
fn main(){
let (sender, receiver) = channel();
(0..5).for_each(|i|{
(0..5).into_par_iter().for_each_with(&sender, |sender, j|{
sender.send(i + j).unwrap();
});
});
}
给我:
8 | (0..5).into_par_iter().for_each_with(&sender, |sender, j|{
| ^^^^^^^ `Sender<_>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `Sender<_>`
= note: required because of the requirements on the impl of `Send` for `&Sender<_>`
(游乐场)
现在我在想这可能是因为我试图克隆一个引用,但是如果我将实际移动sender
到for_each_with()
(ie for_each_with(sender, ...)
) 中,它将被外部循环的第一次迭代消耗:
error[E0507]: cannot move out of `sender`, a captured variable in an `FnMut` closure
(游乐场)。
如何以满足 Rust 编译器的方式实现此模式?