Skip to main content

mln_engine/exec/
thread.rs

1//! The threads mln-rs starts, and the waits for them to end.
2//!
3//! A runtime or a render session owns library threads, which [`spawn`]
4//! starts, and a [`Joined`] waits for one to end when it drops on a host's
5//! thread. On a library thread it doesn't wait, since the thread it would
6//! wait for could be waiting for this one: it leaves it to end alone.
7
8use std::cell::Cell;
9use std::thread::JoinHandle;
10
11use parking_lot::Mutex;
12
13/// The stack size of every thread mln-rs starts. Parsing and evaluating
14/// style JSON, filters and expressions recurses once per nesting level, so
15/// a thread gets this much whatever `RUST_MIN_STACK` or the platform's
16/// default would give it.
17pub(crate) const STACK_SIZE: usize = 2 * 1024 * 1024;
18
19/// A builder for a thread named `name` with a `STACK_SIZE` stack. It isn't a
20/// library thread: a [`Joined`] that drops on it waits, so a thread that a
21/// runtime's or a session's work may wait for starts with [`spawn`].
22pub fn builder(name: impl Into<String>) -> std::thread::Builder {
23    std::thread::Builder::new().name(name.into()).stack_size(STACK_SIZE)
24}
25
26/// Starts a library thread named `name`, with a `STACK_SIZE` stack, that
27/// runs `work`.
28///
29/// # Errors
30///
31/// Fails when the operating system can't start the thread.
32pub fn spawn<T: Send + 'static>(
33    name: impl Into<String>,
34    work: impl FnOnce() -> T + Send + 'static,
35) -> std::io::Result<JoinHandle<T>> {
36    builder(name).spawn(move || {
37        LIBRARY.with(|library| library.set(true));
38        work()
39    })
40}
41
42thread_local! {
43    /// Whether [`spawn`] started this thread.
44    static LIBRARY: Cell<bool> = const { Cell::new(false) };
45}
46
47/// A library thread that ends by itself once its owner lets go of it, which
48/// this waits for when it drops on a host's thread, unless it was
49/// [`detach`](Self::detach)ed. On a library thread, whose locals are still
50/// there, the drop leaves the thread to end alone.
51#[derive(Debug)]
52pub struct Joined(Mutex<Option<JoinHandle<()>>>);
53
54impl Joined {
55    /// Waits for `thread` when this drops on a host's thread.
56    #[must_use]
57    pub fn new(thread: JoinHandle<()>) -> Joined {
58        Joined(Mutex::new(Some(thread)))
59    }
60
61    /// Leaves the thread to end alone: the drop no longer waits for it.
62    pub fn detach(&self) {
63        self.0.lock().take();
64    }
65}
66
67impl Drop for Joined {
68    fn drop(&mut self) {
69        let Some(thread) = self.0.get_mut().take() else { return };
70        if !LIBRARY.try_with(Cell::get).unwrap_or(false) {
71            let _ = thread.join();
72        }
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use std::sync::atomic::{AtomicBool, Ordering};
79    use std::sync::{Arc, mpsc};
80    use std::time::Duration;
81
82    use super::*;
83
84    #[test]
85    fn names_the_thread() {
86        let name = builder("parse").spawn(|| std::thread::current().name().map(str::to_owned)).unwrap().join();
87        assert_eq!(name.unwrap().as_deref(), Some("parse"));
88    }
89
90    /// A library thread that ends once `gate` closes, and the flag that it
91    /// sets as it ends.
92    fn gated() -> (Joined, mpsc::Sender<()>, Arc<AtomicBool>) {
93        let (open, gate) = mpsc::channel::<()>();
94        let ended = Arc::new(AtomicBool::new(false));
95        let flag = Arc::clone(&ended);
96        let thread = spawn("gated", move || {
97            let _ = gate.recv();
98            std::thread::sleep(Duration::from_millis(20));
99            flag.store(true, Ordering::SeqCst);
100        })
101        .unwrap();
102        (Joined::new(thread), open, ended)
103    }
104
105    #[test]
106    fn a_drop_on_a_host_thread_waits_for_the_thread() {
107        let (joined, open, ended) = gated();
108        drop(open);
109        drop(joined);
110        assert!(ended.load(Ordering::SeqCst));
111    }
112
113    #[test]
114    fn a_drop_on_a_library_thread_leaves_the_thread() {
115        let (joined, open, ended) = gated();
116        let owner = spawn("owner", move || drop(joined)).unwrap();
117        owner.join().unwrap();
118        assert!(!ended.load(Ordering::SeqCst));
119        drop(open);
120    }
121
122    #[test]
123    fn a_drop_on_the_thread_itself_leaves_it() {
124        let (joined, joined_here) = mpsc::channel::<Joined>();
125        let thread = spawn("itself", move || drop(joined_here.recv().unwrap())).unwrap();
126        joined.send(Joined::new(thread)).unwrap();
127        // The thread ends, and nothing waits for it.
128        drop(joined);
129    }
130
131    #[test]
132    fn a_detached_thread_is_left_to_end_alone() {
133        let (joined, open, ended) = gated();
134        joined.detach();
135        drop(joined);
136        assert!(!ended.load(Ordering::SeqCst));
137        drop(open);
138    }
139}