mln_engine/exec/
thread.rs1use std::cell::Cell;
9use std::thread::JoinHandle;
10
11use parking_lot::Mutex;
12
13pub(crate) const STACK_SIZE: usize = 2 * 1024 * 1024;
18
19pub fn builder(name: impl Into<String>) -> std::thread::Builder {
23 std::thread::Builder::new().name(name.into()).stack_size(STACK_SIZE)
24}
25
26pub 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 static LIBRARY: Cell<bool> = const { Cell::new(false) };
45}
46
47#[derive(Debug)]
52pub struct Joined(Mutex<Option<JoinHandle<()>>>);
53
54impl Joined {
55 #[must_use]
57 pub fn new(thread: JoinHandle<()>) -> Joined {
58 Joined(Mutex::new(Some(thread)))
59 }
60
61 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 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 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}