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
81    use super::*;
82
83    #[test]
84    fn names_the_thread() {
85        let name = builder("parse").spawn(|| std::thread::current().name().map(str::to_owned)).unwrap().join();
86        assert_eq!(name.unwrap().as_deref(), Some("parse"));
87    }
88
89    /// A library thread that ends once `gate` closes, and the flag that it
90    /// sets as it ends.
91    fn gated() -> (Joined, mpsc::Sender<()>, Arc<AtomicBool>) {
92        let (open, gate) = mpsc::channel::<()>();
93        let ended = Arc::new(AtomicBool::new(false));
94        let flag = Arc::clone(&ended);
95        let thread = spawn("gated", move || {
96            let _ = gate.recv();
97            flag.store(true, Ordering::SeqCst);
98        })
99        .unwrap();
100        (Joined::new(thread), open, ended)
101    }
102
103    #[test]
104    fn a_drop_on_a_host_thread_waits_for_the_thread() {
105        let (joined, open, ended) = gated();
106        drop(open);
107        drop(joined);
108        assert!(ended.load(Ordering::SeqCst));
109    }
110
111    #[test]
112    fn a_drop_on_a_library_thread_leaves_the_thread() {
113        let (joined, open, ended) = gated();
114        let owner = spawn("owner", move || drop(joined)).unwrap();
115        owner.join().unwrap();
116        assert!(!ended.load(Ordering::SeqCst));
117        drop(open);
118    }
119
120    #[test]
121    fn a_drop_on_the_thread_itself_leaves_it() {
122        let (joined, joined_here) = mpsc::channel::<Joined>();
123        let thread = spawn("itself", move || drop(joined_here.recv().unwrap())).unwrap();
124        joined.send(Joined::new(thread)).unwrap();
125        // The thread ends, and nothing waits for it.
126        drop(joined);
127    }
128
129    #[test]
130    fn a_detached_thread_is_left_to_end_alone() {
131        let (joined, open, ended) = gated();
132        joined.detach();
133        drop(joined);
134        assert!(!ended.load(Ordering::SeqCst));
135        drop(open);
136    }
137}