use rayon::ThreadPool;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
struct PoolState {
requested: Option<usize>,
pool: Option<Arc<ThreadPool>>,
}
static POOL_STATE: Mutex<PoolState> = Mutex::new(PoolState {
requested: None,
pool: None,
});
fn lock_state() -> MutexGuard<'static, PoolState> {
POOL_STATE.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn default_num_threads() -> usize {
let available = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
available.saturating_div(4).max(1)
}
pub fn num_threads() -> usize {
lock_state().requested.unwrap_or_else(default_num_threads)
}
pub fn set_num_threads(n: usize) {
assert!(
n >= 1,
"invalid number of threads: 0 was given, but the worker pool needs at least one thread"
);
let available = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
if n > available {
log::warn!(
"{n} threads were requested but only {available} are available; the extra threads will compete for the same cores"
);
}
let mut state = lock_state();
state.requested = Some(n);
if state
.pool
.as_ref()
.is_some_and(|pool| pool.current_num_threads() != n)
{
state.pool = None;
}
}
pub(crate) fn worker_pool() -> Arc<ThreadPool> {
let mut state = lock_state();
let num_threads = state.requested.unwrap_or_else(default_num_threads);
let pool = state.pool.get_or_insert_with(|| {
log::info!("Creating thread pool with {num_threads} threads");
Arc::new(
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build()
.expect("failed to build the rayon worker pool"),
)
});
Arc::clone(pool)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pool_follows_the_setting() {
let before = num_threads();
let default = default_num_threads();
assert!(default >= 1);
set_num_threads(3);
assert_eq!(num_threads(), 3);
let old = worker_pool();
assert_eq!(old.current_num_threads(), 3);
set_num_threads(2);
let new = worker_pool();
assert_eq!(new.current_num_threads(), 2);
assert_eq!(old.current_num_threads(), 3);
assert_eq!(old.install(|| 7), 7);
set_num_threads(before);
}
#[test]
#[should_panic(expected = "invalid number of threads")]
fn zero_threads_is_refused() {
set_num_threads(0);
}
}