use rayon::prelude::*;
use crate::YscvPool;
pub trait ParallelScope: Send + Sync {
fn install_session(&self, f: &mut dyn FnMut());
fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync));
fn par_chunks_mut_dyn(
&self,
data: &mut [f32],
chunk_size: usize,
f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
);
fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send));
fn current_worker_index(&self) -> Option<usize>;
fn num_threads(&self) -> usize;
}
impl ParallelScope for YscvPool {
fn install_session(&self, f: &mut dyn FnMut()) {
self.enter_section(|section| {
let _guard = section.install_tls();
f();
});
}
fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync)) {
self.par_for_each_index(count, f);
}
fn par_chunks_mut_dyn(
&self,
data: &mut [f32],
chunk_size: usize,
f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
) {
if chunk_size == 0 || data.is_empty() {
return;
}
let len = data.len();
let n_chunks = len.div_ceil(chunk_size);
struct PtrWrap(*mut f32);
impl PtrWrap {
#[inline]
const fn as_ptr(&self) -> *mut f32 {
self.0
}
}
#[allow(unsafe_code)]
unsafe impl Send for PtrWrap {}
#[allow(unsafe_code)]
unsafe impl Sync for PtrWrap {}
let wrap = PtrWrap(data.as_mut_ptr());
self.par_for_each_index(n_chunks, move |i| {
let start = i * chunk_size;
let end = (start + chunk_size).min(len);
#[allow(unsafe_code)]
let chunk =
unsafe { std::slice::from_raw_parts_mut(wrap.as_ptr().add(start), end - start) };
f(i, chunk);
});
}
fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
self.join(a, b);
}
fn current_worker_index(&self) -> Option<usize> {
self.current_worker_index()
}
fn num_threads(&self) -> usize {
YscvPool::num_threads(self)
}
}
impl ParallelScope for rayon::ThreadPool {
fn install_session(&self, f: &mut dyn FnMut()) {
f();
}
fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync)) {
(0..count).into_par_iter().for_each(f);
}
fn par_chunks_mut_dyn(
&self,
data: &mut [f32],
chunk_size: usize,
f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
) {
if chunk_size == 0 || data.is_empty() {
return;
}
data.par_chunks_mut(chunk_size)
.enumerate()
.for_each(|(i, c)| f(i, c));
}
fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
rayon::join(a, b);
}
fn current_worker_index(&self) -> Option<usize> {
rayon::current_thread_index()
}
fn num_threads(&self) -> usize {
self.current_num_threads()
}
}
pub struct AmbientRayonScope {
num_threads: usize,
}
impl AmbientRayonScope {
pub fn new(num_threads: usize) -> Self {
Self {
num_threads: num_threads.max(1),
}
}
}
impl ParallelScope for AmbientRayonScope {
fn install_session(&self, f: &mut dyn FnMut()) {
f();
}
fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync)) {
(0..count).into_par_iter().for_each(f);
}
fn par_chunks_mut_dyn(
&self,
data: &mut [f32],
chunk_size: usize,
f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
) {
if chunk_size == 0 || data.is_empty() {
return;
}
data.par_chunks_mut(chunk_size)
.enumerate()
.for_each(|(i, c)| f(i, c));
}
fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
rayon::join(a, b);
}
fn current_worker_index(&self) -> Option<usize> {
rayon::current_thread_index()
}
fn num_threads(&self) -> usize {
self.num_threads
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
fn sum_via_scope(scope: &dyn ParallelScope, count: usize) -> usize {
let total = Arc::new(AtomicUsize::new(0));
let t = Arc::clone(&total);
let f: Box<dyn Fn(usize) + Send + Sync> = Box::new(move |i| {
t.fetch_add(i, Ordering::Relaxed);
});
scope.par_for_each_index(count, f.as_ref());
total.load(Ordering::Relaxed)
}
#[test]
fn yscv_pool_scope_sums_correctly() {
let pool = YscvPool::new(4).unwrap();
assert_eq!(sum_via_scope(&pool, 1000), 499_500);
}
#[test]
fn rayon_pool_scope_sums_correctly() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(4)
.build()
.unwrap();
assert_eq!(sum_via_scope(&pool, 1000), 499_500);
}
fn doubles_chunks_via_scope(scope: &dyn ParallelScope) -> Vec<f32> {
let mut data: Vec<f32> = (0..32).map(|i| i as f32).collect();
let f: Box<dyn Fn(usize, &mut [f32]) + Send + Sync> = Box::new(|_idx, chunk| {
for v in chunk {
*v *= 2.0;
}
});
scope.par_chunks_mut_dyn(&mut data, 4, f.as_ref());
data
}
#[test]
fn yscv_pool_par_chunks_mut_dyn_matches_rayon() {
let pool = YscvPool::new(4).unwrap();
let out = doubles_chunks_via_scope(&pool);
let expected: Vec<f32> = (0..32).map(|i| (i as f32) * 2.0).collect();
assert_eq!(out, expected);
}
#[test]
fn rayon_pool_par_chunks_mut_dyn_matches_rayon() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(4)
.build()
.unwrap();
let out = doubles_chunks_via_scope(&pool);
let expected: Vec<f32> = (0..32).map(|i| (i as f32) * 2.0).collect();
assert_eq!(out, expected);
}
#[test]
fn par_chunks_mut_dyn_handles_uneven_last_chunk() {
let pool = YscvPool::new(2).unwrap();
let mut data: Vec<f32> = vec![1.0; 17];
let f: Box<dyn Fn(usize, &mut [f32]) + Send + Sync> = Box::new(|idx, chunk| {
for v in chunk {
*v += idx as f32;
}
});
pool.par_chunks_mut_dyn(&mut data, 5, f.as_ref());
let expected = vec![
1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0,
];
assert_eq!(data, expected);
}
#[test]
fn yscv_pool_current_worker_index_is_some_inside_install() {
let pool = YscvPool::new(2).unwrap();
let idx = pool.install(|| pool.current_worker_index());
assert!(idx.is_some(), "expected Some(worker_idx) inside install");
}
#[test]
fn yscv_pool_current_worker_index_is_none_on_main() {
let pool = YscvPool::new(2).unwrap();
assert_eq!(pool.current_worker_index(), None);
}
}