From 15501132916dfbc24f23b619e6d5408f258fc0d9 Mon Sep 17 00:00:00 2001 From: Jonas Maier <> Date: Wed, 11 Mar 2026 12:30:07 +0100 Subject: can wait for threads & processes with a timeout now --- src/wait/thread.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/wait/thread.rs (limited to 'src/wait/thread.rs') diff --git a/src/wait/thread.rs b/src/wait/thread.rs new file mode 100644 index 0000000..0eadc3c --- /dev/null +++ b/src/wait/thread.rs @@ -0,0 +1,51 @@ +use std::{ + sync::mpsc::{Receiver, channel}, + thread::JoinHandle, time::Duration, +}; + +use crate::defer; + +pub struct ThreadWaiter { + handle: JoinHandle, + chan: Receiver<()>, + done: bool, +} + +pub fn spawn(fun: F) -> ThreadWaiter +where + T: Send + 'static, + F: Send + 'static, + F: FnOnce() -> T, +{ + let (tx, rx) = channel(); + + let handle = std::thread::spawn(move || { + defer! { + let _ = tx.send(()); + }; + fun() + }); + + ThreadWaiter { + handle, + chan: rx, + done: false, + } +} + +impl ThreadWaiter { + pub fn try_join(&mut self, timeout_ms: u16) -> bool { + if self.done { + return true; + } + + if let Ok(()) = self.chan.recv_timeout(Duration::from_millis(timeout_ms as _)) { + self.done = true; + } + + self.done + } + pub fn into_inner(self) -> JoinHandle { + self.handle + } +} -- cgit v1.2.3