Cal*_*rey 6 multithreading clone rust
我正在研究基于 C++ 代码库(PBRT,如果有人熟悉的话)的光线追踪器的 Rust 实现。C++ 版本定义的类之一是一系列采样器,以减少渲染图像中的噪声。在渲染过程中,每当需要随机数时,该采样器就会被克隆到每个渲染线程中。这就是我在 Rust 中选择的做法,我承认这有点复杂:
#[derive(Clone)]
pub struct PixelSampler {
samples_1d: Vec<Vec<f64>>,
samples_2d: Vec<Vec<Point2<f64>>>,
current_1d_dimension: i32,
current_2d_dimension: i32,
rng: rngs::ThreadRng
}
pub enum Samplers {
StratifiedSampler {x_samples: i64, y_samples: i64, jitter_samples: bool, pixel: PixelSampler },
ZeroTwoSequenceSampler { pixel: PixelSampler }
}
impl Clone for Samplers {
fn clone(&self) -> Self {
match self {
Samplers::StratifiedSampler { x_samples, y_samples, jitter_samples, pixel } => {
Samplers::StratifiedSampler {x_samples: *x_samples,
y_samples: *y_samples,
jitter_samples: *jitter_samples,
pixel: pixel.clone() }
}
Samplers::ZeroTwoSequenceSampler { pixel } => { Samplers::ZeroTwoSequenceSampler{ pixel: pixel.clone() } }
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我还有一个Integrator它有一个Samplers变体字段。在我的主渲染循环中,我为每个线程运行以下循环:
for _ in 0..NUM_THREADS {
let int_clone = integrator.clone(); // integrator just contains a Samplers
thread_vec.push(thread::spawn(move || {
loop {
// do main rendering loop
}
}));
}
Run Code Online (Sandbox Code Playgroud)
但是当我用这个编译时,我收到错误:
“该特征std::marker::Send没有实现std::ptr::NonNull<rand::rngs::adapter::reseeding::ReseedingRng<rand_chacha::chacha::ChaCha20Core, rand_core::os::OsRng>>”。
我的理解是,因为我只将克隆版本移动到线程中,所以Send不需要实现。我究竟做错了什么?
正如thread_rng()文档所说,它是:
[...]本质上只是对线程本地内存中 PRNG 的引用。
因此,通过克隆“rng”,您并没有复制生成器及其状态(我认为这是您的意图),而是创建了线程本地 RNG 的新句柄。这个句柄不是故意的,Send因为它访问线程本地 RNG 时不加锁以提高效率。
如果您希望结构体包含实际的 RNG,并克隆该结构体以复制它,则可以使用该StdRng类型,这是推荐的、高效且安全的 RNG。要实例化它,请使用特征中的方法SeedableRng。例如:
#[derive(Clone)]
pub struct PixelSampler {
samples_1d: Vec<Vec<f64>>,
samples_2d: Vec<Vec<Point2<f64>>>,
current_1d_dimension: i32,
current_2d_dimension: i32,
rng: StdRng,
}
// ...
let sampler = Samplers::ZeroTwoSequenceSampler {
pixel: PixelSampler {
samples_1d: vec![],
samples_2d: vec![],
current_1d_dimension: 0,
current_2d_dimension: 0,
rng: SeedableRng::from_entropy(),
},
};
// compiles because StdRng is Send
std::thread::spawn(move || sampler).join().unwrap();
Run Code Online (Sandbox Code Playgroud)
操场上的完整例子。