melodium_engine/
runtime.rs1use async_executor::{Executor, Task};
8use std::future::Future;
9use std::sync::Once;
10
11pub const THREADS_VARIABLE: &str = "MELODIUM_THREADS";
13
14static EXECUTOR: Executor<'static> = Executor::new();
15static START: Once = Once::new();
16
17pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
21 START.call_once(start);
22 EXECUTOR.spawn(future)
23}
24
25pub fn threads() -> usize {
27 std::env::var(THREADS_VARIABLE)
28 .ok()
29 .and_then(|threads| threads.trim().parse::<usize>().ok())
30 .filter(|threads| *threads > 0)
31 .unwrap_or_else(|| {
32 std::thread::available_parallelism()
33 .map(|cores| cores.get())
34 .unwrap_or(1)
35 })
36}
37
38fn start() {
39 for number in 0..threads() {
40 std::thread::Builder::new()
41 .name(format!("melodium-{number}"))
42 .spawn(|| loop {
43 let _ = std::panic::catch_unwind(|| {
46 smol::block_on(EXECUTOR.run(std::future::pending::<()>()))
47 });
48 })
49 .expect("cannot start the threads running tracks");
50 }
51}