use std::sync::{OnceLock, mpsc};
type Job = Box<dyn FnOnce() + Send + 'static>;
struct Pool {
senders: Vec<mpsc::Sender<Job>>,
}
static POOL: OnceLock<Pool> = OnceLock::new();
fn pool() -> &'static Pool {
POOL.get_or_init(|| {
let workers = std::thread::available_parallelism()
.map(std::num::NonZeroUsize::get)
.unwrap_or(1);
let mut senders = Vec::with_capacity(workers);
for index in 0..workers {
let (tx, rx) = mpsc::channel::<Job>();
let spawned = std::thread::Builder::new()
.name(format!("fp-pool-{index}"))
.spawn(move || {
while let Ok(job) = rx.recv() {
job();
}
});
if spawned.is_ok() {
senders.push(tx);
}
}
Pool { senders }
})
}
#[must_use]
pub fn worker_count() -> usize {
pool().senders.len()
}
pub fn run<T: Send + 'static>(jobs: Vec<Box<dyn FnOnce() -> T + Send + 'static>>) -> Vec<T> {
let count = jobs.len();
if count == 0 {
return Vec::new();
}
let pool = pool();
let workers = pool.senders.len();
if count == 1 || workers == 0 {
return jobs.into_iter().map(|job| job()).collect();
}
let (result_tx, result_rx) = mpsc::channel::<(usize, T)>();
let mut dispatched = 0usize;
for (index, job) in jobs.into_iter().enumerate() {
let result_tx = result_tx.clone();
let wrapped: Job = Box::new(move || {
let _ = result_tx.send((index, job()));
});
match pool.senders[index % workers].send(wrapped) {
Ok(()) => dispatched += 1,
Err(mpsc::SendError(returned)) => {
returned();
dispatched += 1;
}
}
}
drop(result_tx);
let mut slots: Vec<Option<T>> = Vec::with_capacity(count);
slots.resize_with(count, || None);
for _ in 0..dispatched {
match result_rx.recv() {
Ok((index, value)) => slots[index] = Some(value),
Err(mpsc::RecvError) => break,
}
}
slots
.into_iter()
.map(|slot| slot.expect("every dispatched job reports exactly one result"))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_preserves_submission_order_regardless_of_completion_order() {
let jobs: Vec<Box<dyn FnOnce() -> usize + Send + 'static>> = (0..64usize)
.map(|i| {
Box::new(move || {
let spin = (64 - i) * 20_000;
let mut acc = 0usize;
for x in 0..spin {
acc = acc.wrapping_add(x);
}
std::hint::black_box(acc);
i
}) as Box<dyn FnOnce() -> usize + Send + 'static>
})
.collect();
assert_eq!(run(jobs), (0..64usize).collect::<Vec<_>>());
}
#[test]
fn run_handles_empty_single_and_repeated_dispatch() {
assert!(run::<usize>(Vec::new()).is_empty());
let one: Vec<Box<dyn FnOnce() -> usize + Send + 'static>> = vec![Box::new(|| 7)];
assert_eq!(run(one), vec![7]);
for round in 0..50usize {
let jobs: Vec<Box<dyn FnOnce() -> usize + Send + 'static>> = (0..8usize)
.map(|i| Box::new(move || i * round) as Box<dyn FnOnce() -> usize + Send + 'static>)
.collect();
assert_eq!(
run(jobs),
(0..8usize).map(|i| i * round).collect::<Vec<_>>()
);
}
}
#[test]
fn worker_count_is_positive_on_a_host_that_can_spawn() {
assert!(worker_count() >= 1, "pool must have at least one worker");
}
}