use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use tilo_lock::MutexRecover as _;
#[cfg(not(target_family = "wasm"))]
pub(crate) const APP_BLOCKING_THREADS: usize = 8;
#[cfg(not(target_family = "wasm"))]
pub(crate) const DAEMON_BLOCKING_THREADS: usize = 32;
pub(crate) const BLOCK_ON_BLOCKING_THREADS: usize = 4;
type Job = Box<dyn FnOnce() + Send + 'static>;
pub(crate) struct JobPool {
queue: Mutex<Sender<Job>>,
}
impl JobPool {
pub(crate) fn start(name: &str, threads: usize) -> std::io::Result<Self> {
let (queue, jobs) = std::sync::mpsc::channel::<Job>();
let jobs = Arc::new(Mutex::new(jobs));
let mut started = 0_usize;
let mut last_error = None;
for index in 0..threads.max(1) {
let jobs = Arc::clone(&jobs);
match crate::spawn_thread(format!("{name}-{index}"), move || drain(&jobs)) {
Ok(_) => started = started.saturating_add(1),
Err(error) => last_error = Some(error),
}
}
match (started, last_error) {
(0, Some(error)) => Err(error),
_ => Ok(Self {
queue: Mutex::new(queue),
}),
}
}
pub(crate) fn submit(&self, job: impl FnOnce() + Send + 'static) -> bool {
self.queue.lock_recover().send(Box::new(job)).is_ok()
}
}
fn drain(jobs: &Mutex<Receiver<Job>>) {
loop {
let job = jobs.lock_recover().recv();
let Ok(job) = job else { return };
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).is_err() {
tracing::warn!("pool job panicked");
}
}
}