use async_executor::{Executor, Task};
use std::future::Future;
use std::sync::Once;
pub const THREADS_VARIABLE: &str = "MELODIUM_THREADS";
static EXECUTOR: Executor<'static> = Executor::new();
static START: Once = Once::new();
pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
START.call_once(start);
EXECUTOR.spawn(future)
}
pub fn threads() -> usize {
std::env::var(THREADS_VARIABLE)
.ok()
.and_then(|threads| threads.trim().parse::<usize>().ok())
.filter(|threads| *threads > 0)
.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|cores| cores.get())
.unwrap_or(1)
})
}
fn start() {
for number in 0..threads() {
std::thread::Builder::new()
.name(format!("melodium-{number}"))
.spawn(|| loop {
let _ = std::panic::catch_unwind(|| {
smol::block_on(EXECUTOR.run(std::future::pending::<()>()))
});
})
.expect("cannot start the threads running tracks");
}
}