latexml_core/util/thread.rs
1//! Thread-spawn helper that degrades instead of panicking.
2//!
3//! A bare `std::thread::spawn` (and `Builder::spawn(..).expect(..)`) panics when
4//! the OS refuses a new thread — `EAGAIN`/`WouldBlock` under fleet thread or
5//! memory exhaustion. On the cortex fleet those panics surfaced as
6//! `imageprocessing:worker_panicked` (a per-paper conversion aborted) and, at
7//! the top-level and kpathsea-prewarm spawns, as whole-document failures. For
8//! best-effort background work — a stderr drain, the kpathsea prewarm — a
9//! missing thread is harmless, so the spawn should degrade to `None`.
10
11use std::thread::{Builder, JoinHandle};
12
13/// Spawn `f` on a named thread, returning `None` (instead of panicking) if the
14/// OS refuses the thread. Use only where a missing thread is safe: the work is
15/// best-effort and its absence changes no output. Load-bearing threads must
16/// keep propagating the error.
17pub fn try_spawn_or_degrade<F, T>(name: &str, f: F) -> Option<JoinHandle<T>>
18where
19 F: FnOnce() -> T + Send + 'static,
20 T: Send + 'static,
21{
22 Builder::new().name(name.to_owned()).spawn(f).ok()
23}
24
25#[cfg(test)]
26mod tests {
27 use super::*;
28
29 #[test]
30 fn spawns_and_returns_a_handle() {
31 let h = try_spawn_or_degrade("test-worker", || 21 * 2);
32 assert_eq!(
33 h.expect("a thread spawns under normal limits")
34 .join()
35 .unwrap(),
36 42
37 );
38 }
39}