【发布时间】:2022-11-12 15:01:51
【问题描述】:
我通过实现光线追踪器来学习 rust。我有一个单线程的工作原型,我正在尝试使其成为多线程。
在我的代码中,我有一个采样器,它基本上是StdRng::seed_from_u64(123) 的包装器(当我添加不同类型的采样器时,它会改变),因为StdRNG 是可变的。我需要有一个可重复的行为,这就是我播种随机数生成器的原因。
在我的渲染循环中,我以下列方式使用采样器
let mut sampler = create_sampler(&self.sampler_value);
let sample_count = sampler.sample_count();
println!("Rendering ...");
let progress_bar = get_progress_bar(image.size());
// Generate multiple rays for each pixel in the image
for y in 0..image.size_y {
for x in 0..image.size_x {
image[(x, y)] = (0..sample_count)
.into_iter()
.map(|_| {
let pixel = Vec2::new(x as f32, y as f32) + sampler.next2f();
let ray = self.camera.generate_ray(&pixel);
self.integrator.li(self, &mut sampler, &ray)
})
.sum::<Vec3>()
/ (sample_count as f32);
progress_bar.inc(1);
}
}
当我用par_into_iter 替换into_iter 时,编译器会告诉我不能将sampler 借用为可变的,因为它是Fn 闭包中的捕获变量
在这种情况下我该怎么办?
谢谢!
附:如果它有任何用处,这是回购:https://github.com/jgsimard/rustrt
【问题讨论】:
-
如果你保持一个单身的对于所有线程的 RNG,无论幕后使用何种锁定/原子机制,您都将终止并行性,因为您将在每个线程的每次迭代中都有缓存失效。您可能需要使用手工解决方案进行并行化:明确选择线程数,将图像沿 y 除以该数字(类似于
chunks_mut()),为每个线程提供其自己的RNG(如您所愿),并让这些线程工作独立地在他们的部分图像切片上。
标签: rust raytracing rayon