use crate::utils::{DefaultRandom, Random, ThreadPool};
use std::sync::Arc;
#[derive(Clone)]
pub struct Environment {
pub random: Arc<dyn Random + Send + Sync>,
pub parallelism: Parallelism,
}
impl Environment {
pub fn new(random: Arc<dyn Random + Send + Sync>, parallelism: Parallelism) -> Self {
Self { random, parallelism }
}
}
impl Default for Environment {
fn default() -> Self {
Environment::new(Arc::new(DefaultRandom::default()), Parallelism::default())
}
}
#[derive(Clone)]
pub struct Parallelism {
available_cpus: usize,
#[allow(clippy::rc_buffer)]
thread_pools: Option<Arc<Vec<ThreadPool>>>,
}
impl Default for Parallelism {
fn default() -> Self {
Self { available_cpus: get_cpus(), thread_pools: None }
}
}
impl Parallelism {
pub fn new(num_thread_pools: usize, threads_per_pool: usize) -> Self {
let thread_pools = (0..num_thread_pools).map(|_| ThreadPool::new(threads_per_pool)).collect();
Self { available_cpus: get_cpus(), thread_pools: Some(Arc::new(thread_pools)) }
}
pub fn available_cpus(&self) -> usize {
self.available_cpus
}
pub fn thread_pool_execute<OP, R>(&self, idx: usize, op: OP) -> R
where
OP: FnOnce() -> R + Send,
R: Send,
{
if let Some(thread_pool) = self.thread_pools.as_ref().and_then(|tps| tps.get(idx)) {
thread_pool.execute(op)
} else {
op()
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn get_cpus() -> usize {
num_cpus::get()
}
#[cfg(target_arch = "wasm32")]
fn get_cpus() -> usize {
1
}