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
52
53
54
55
56
57
58
59
use std::env;
use std::thread::{self, JoinHandle};
pub fn spawn_thread<F, T>(f: F) -> ThreadHandle<F, T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
{
let single = env::var("PERSEUS_CLI_SEQUENTIAL").is_ok();
if single {
ThreadHandle {
join_handle: None,
f: Some(f),
}
} else {
let join_handle = thread::spawn(f);
ThreadHandle {
join_handle: Some(join_handle),
f: None,
}
}
}
pub struct ThreadHandle<F, T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
{
join_handle: Option<JoinHandle<T>>,
f: Option<F>,
}
impl<F, T> ThreadHandle<F, T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
{
pub fn join(
self,
) -> Result<T, std::boxed::Box<(dyn std::any::Any + std::marker::Send + 'static)>> {
if let Some(join_handle) = self.join_handle {
join_handle.join()
} else if let Some(f) = self.f {
let output = f();
Ok(output)
} else {
unreachable!();
}
}
}