实际上,您自己回答了您的问题——所有需要在线程之间共享的闭包都必须是 Sync,而 Rayon 的 API 只是通过 trait bound 要求它们是 Sync。参见例如documentation of ParallelIterator::map(),它将方法指定为
fn map<F, R>(self, map_op: F) -> Map<Self, F> where
F: Fn(Self::Item) -> R + Sync + Send,
R: Send,
这里没有任何更深层次的魔法——每当 Rayon 以一种要求它为 Sync 的方式使用闭包时,例如通过将其传递给较低级别的 API,Rayon 使用 Sync 特征绑定来限制相应的参数类型。这反过来确保闭包中存储的所有内容都是Sync,因此您不能在闭包中存储任何RefCell。
在这种情况下,您也可以向编译器询问解释。例如,如果您尝试编译此代码
use std::cell::RefCell;
use rayon::prelude::*;
fn main() {
let c = RefCell::new(5);
let _ = [1, 2, 3]
.par_iter()
.map(|i| i * *c.borrow())
.sum();
}
您将收到此错误 (playground)
error[E0277]: `std::cell::RefCell<i32>` cannot be shared between threads safely
--> src/main.rs:10:10
|
10 | .map(|i| i * *c.borrow())
| ^^^ `std::cell::RefCell<i32>` cannot be shared between threads safely
|
= help: within `[closure@src/main.rs:10:14: 10:33 c:&std::cell::RefCell<i32>]`, the trait `std::marker::Sync` is not implemented for `std::cell::RefCell<i32>`
= note: required because it appears within the type `&std::cell::RefCell<i32>`
= note: required because it appears within the type `[closure@src/main.rs:10:14: 10:33 c:&std::cell::RefCell<i32>]`
虽然编译器很遗憾没有直接提及 map() 的参数的 trait bound,但它仍然指向相关方法,并解释它期望闭包是 Sync,以及它的原因不。