use std::thread::{self, JoinHandle};
pub fn spawn_thread<F, T>(f: F, sequential: bool) -> ThreadHandle<F, T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
{
if sequential {
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!();
}
}
}