我正在研究基于C ++代码库(如果有人熟悉的话,请使用PBRT)的Ray Tracer的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() } }
}
}
}
然后我也有一个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
}
}));
}
但是当我用这个编译时,我得到了错误:
“该特性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 SeedableRng is Send
std::thread::spawn(move || sampler).join().unwrap();
在操场上的完整例子。