Skip to main content

tilo_rt/
cpu.rs

1//! CPU-bound bulk work, on a dedicated pool.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::OnceLock;
6use std::task::{Context, Poll};
7
8use tokio::sync::oneshot;
9
10use crate::Error;
11
12/// The process-wide CPU pool: one named thread (`tilo-cpu-N`) per core.
13///
14/// Use it directly (`cpu_pool().install(|| items.par_iter()…)`) for
15/// data-parallel work from a synchronous thread; from async code, use
16/// [`cpu()`].
17///
18/// # Panics
19///
20/// When the OS refuses to start the pool's threads.
21///
22/// In a browser the pool is the page thread alone: `install` and parallel
23/// iterators run sequentially on the caller.
24#[allow(
25    clippy::expect_used,
26    reason = "a process that cannot start its compute threads cannot do the work it was asked for"
27)]
28pub fn cpu_pool() -> &'static rayon::ThreadPool {
29    static POOL: OnceLock<rayon::ThreadPool> = OnceLock::new();
30    POOL.get_or_init(|| {
31        crate::panic_boundary::abort_outside_boundaries_in_release();
32        let builder = rayon::ThreadPoolBuilder::new();
33        #[cfg(target_family = "wasm")]
34        let builder = builder.num_threads(1).use_current_thread();
35        builder
36            .thread_name(|index| format!("tilo-cpu-{index}"))
37            .build()
38            .expect("start the CPU pool")
39    })
40}
41
42const LIBRARY_THREADS: usize = 16;
43
44/// Build rayon's process-wide pool before a library builds it, so its size is
45/// [`LIBRARY_THREADS`] rather than one worker per logical CPU: a library that
46/// first calls `par_iter` (a message layer's group tree, a renderer, a text
47/// layout) builds that pool itself, and on a machine with hundreds of CPUs it
48/// then holds hundreds of idle threads for work that is a handful of items.
49/// Bulk work a person waits for goes through [`cpu_pool`], which is sized per
50/// core on purpose.
51pub fn bound_parallel_pool() {
52    static POOL: std::sync::Once = std::sync::Once::new();
53    POOL.call_once(|| {
54        let threads = std::thread::available_parallelism()
55            .map_or(1, std::num::NonZero::get)
56            .min(LIBRARY_THREADS);
57        let _ = rayon::ThreadPoolBuilder::new()
58            .num_threads(threads)
59            .thread_name(|index| format!("tilo-parallel-{index}"))
60            .build_global();
61    });
62}
63
64/// Run `work` on the [`cpu_pool`] and await its result.
65///
66/// Hashing, chunking, compression, image decoding and index building belong
67/// here: on an async worker they stall every task behind them, and on a
68/// blocking pool they compete with blocking I/O for threads sized for
69/// waiting, not computing.
70///
71/// In a browser the work runs on the page thread as an app task, after the
72/// caller yields.
73pub fn cpu<R, F>(work: F) -> CpuTask<R>
74where
75    F: FnOnce() -> R + Send + 'static,
76    R: Send + 'static,
77{
78    let (tx, rx) = oneshot::channel();
79    let job = move || {
80        if tx.is_closed() {
81            return;
82        }
83        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work));
84        let _ = tx.send(outcome.ok());
85    };
86    #[cfg(not(target_family = "wasm"))]
87    cpu_pool().spawn(job);
88    #[cfg(target_family = "wasm")]
89    crate::app::spawn_job(job);
90    CpuTask(rx)
91}
92
93#[derive(Debug)]
94pub struct CpuTask<R>(oneshot::Receiver<Option<R>>);
95
96impl<R> Future for CpuTask<R> {
97    type Output = Result<R, Error>;
98
99    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
100        Pin::new(&mut self.0)
101            .poll(cx)
102            .map(|received| received.ok().flatten().ok_or(Error::TaskFailed))
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn cpu_work_runs_on_the_pool_and_reports_panics() {
112        {
113            let (name, in_runtime) = crate::block_on(cpu(|| {
114                (
115                    std::thread::current().name().map(str::to_owned),
116                    crate::in_runtime(),
117                )
118            }))
119            .unwrap()
120            .unwrap();
121            assert!(name.unwrap().starts_with("tilo-cpu-"));
122            assert!(!in_runtime);
123        }
124        {
125            let result = crate::block_on(cpu(|| -> u8 { panic!("job failure") })).unwrap();
126            assert!(matches!(result, Err(Error::TaskFailed)));
127        }
128    }
129}