Skip to main content

melodium_engine/
runtime.rs

1//! Threads running the tracks of programs.
2//!
3//! Tracks, and continuous tasks of models, run on a pool of threads owned by the engine.
4//! It has one thread per core, unless the `MELODIUM_THREADS` environment variable gives
5//! another number. The pool starts with the first task, and lives as long as the process.
6
7use async_executor::{Executor, Task};
8use std::future::Future;
9use std::sync::Once;
10
11/// Environment variable giving the number of threads running tracks.
12pub const THREADS_VARIABLE: &str = "MELODIUM_THREADS";
13
14static EXECUTOR: Executor<'static> = Executor::new();
15static START: Once = Once::new();
16
17/// Runs `future` on the threads of the engine.
18///
19/// The task is cancelled when the returned [`Task`] is dropped, unless it is detached.
20pub 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
25/// Number of threads running tracks, from `MELODIUM_THREADS` or the number of cores.
26pub 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                // A panicking task gives its panic to whoever awaits it, the thread
44                // goes on running others.
45                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}