1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
use std::{
sync::mpsc::{Receiver, channel},
thread::JoinHandle, time::Duration,
};
use crate::defer;
pub struct ThreadWaiter<T> {
handle: JoinHandle<T>,
chan: Receiver<()>,
done: bool,
}
pub fn spawn<T, F>(fun: F) -> ThreadWaiter<T>
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<T> ThreadWaiter<T> {
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<T> {
self.handle
}
}
|