use std::cell::Cell;
thread_local! {
static SEQUENTIAL: Cell<bool> = const { Cell::new(false) };
}
pub fn sequential<R>(f: impl FnOnce() -> R) -> R {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
SEQUENTIAL.with(|s| s.set(self.0));
}
}
let _restore = Restore(SEQUENTIAL.with(|s| s.replace(true)));
f()
}
pub fn n_threads() -> usize {
if SEQUENTIAL.with(Cell::get) {
return 1;
}
#[cfg(feature = "parallel")]
{
rayon::current_num_threads()
}
#[cfg(not(feature = "parallel"))]
{
1
}
}
pub const PARALLEL_MIN_WORK: usize = 1 << 19;
fn on_pool(work: usize) -> bool {
n_threads() > 1 && work >= PARALLEL_MIN_WORK
}
const CHUNKS_PER_THREAD: usize = 4;
pub fn run_on_pool<'a, F: FnOnce() + Send + 'a>(jobs: impl IntoIterator<Item = F>) {
#[cfg(feature = "parallel")]
if n_threads() > 1 {
let jobs: Vec<F> = jobs.into_iter().collect();
let fpu = crate::fpu_check::FpuContext::current();
rayon::scope(|scope| {
for job in jobs {
scope.spawn(move |_| fpu.run(job));
}
});
return;
}
for job in jobs {
job();
}
}
pub fn for_each_chunk<T: Send>(out: &mut [T], work: usize, f: impl Fn(usize, &mut [T]) + Sync) {
if out.len() <= 1 || !on_pool(work) {
f(0, out);
return;
}
let chunk_len = out
.len()
.div_ceil(n_threads().min(out.len()) * CHUNKS_PER_THREAD);
let f = &f;
run_on_pool(
out.chunks_mut(chunk_len)
.enumerate()
.map(|(c, chunk)| move || f(c * chunk_len, chunk)),
);
}
pub fn map_on_pool<R: Send>(n: usize, work: usize, f: impl Fn(usize) -> R + Sync) -> Vec<R> {
if !on_pool(work) {
return (0..n).map(f).collect();
}
let mut slots: Vec<Option<R>> = (0..n).map(|_| None).collect();
let f = &f;
run_on_pool(
slots
.iter_mut()
.enumerate()
.map(|(i, slot)| move || *slot = Some(f(i))),
);
slots
.into_iter()
.map(|r| r.expect("every job has run"))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn for_each_chunk_matches_serial() {
let fill = |work| {
let mut out = vec![0.0f64; 10_000];
for_each_chunk(&mut out, work, |start, chunk| {
for (i, x) in chunk.iter_mut().enumerate() {
*x = ((start + i) as f64 * 0.37).sin();
}
});
out
};
assert_eq!(fill(usize::MAX), fill(0));
assert_eq!(fill(0)[9_999], (9_999.0f64 * 0.37).sin());
}
#[test]
fn map_on_pool_keeps_the_order() {
assert_eq!(
map_on_pool(100, usize::MAX, |i| i * i),
(0..100).map(|i| i * i).collect::<Vec<_>>()
);
assert!(map_on_pool(0, usize::MAX, |i| i).is_empty());
assert_eq!(map_on_pool(3, 0, |i| i), vec![0, 1, 2]);
}
#[cfg(feature = "parallel")]
#[test]
fn map_on_pool_sends_a_single_large_item_to_the_pool() {
let thread_index = |work| map_on_pool(1, work, |_| rayon::current_thread_index())[0];
assert_eq!(thread_index(0), None);
if n_threads() > 1 {
assert!(thread_index(usize::MAX).is_some());
}
}
#[cfg(feature = "parallel")]
#[test]
fn uses_the_installed_pool() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(1)
.build()
.unwrap();
pool.install(|| {
assert_eq!(n_threads(), 1);
let ids = map_on_pool(8, usize::MAX, |_| std::thread::current().id());
assert!(ids.iter().all(|id| *id == ids[0]));
});
}
#[test]
fn sequential_runs_on_the_calling_thread() {
let caller = std::thread::current().id();
let on_caller = || {
map_on_pool(16, usize::MAX, |_| std::thread::current().id())
.iter()
.all(|id| *id == caller)
};
sequential(|| {
assert_eq!(n_threads(), 1);
assert!(on_caller());
sequential(|| assert!(on_caller()));
assert_eq!(n_threads(), 1);
});
let panicked = std::panic::catch_unwind(|| sequential(|| panic!("in sequential")));
assert!(panicked.is_err());
assert!(!SEQUENTIAL.with(Cell::get));
#[cfg(not(feature = "parallel"))]
assert_eq!(n_threads(), 1);
}
}