33 lines
647 B
Rust
33 lines
647 B
Rust
use crossbeam_channel::{Receiver, bounded};
|
|
|
|
#[derive(Debug)]
|
|
pub struct AsyncJob<T> {
|
|
receiver: Receiver<T>,
|
|
}
|
|
|
|
impl<T> AsyncJob<T> {
|
|
pub fn wait(self) -> T {
|
|
self.receiver
|
|
.recv()
|
|
.expect("AsyncJob worker thread panicked or disconnected")
|
|
}
|
|
|
|
pub fn is_ready(&self) -> bool {
|
|
!self.receiver.is_empty()
|
|
}
|
|
}
|
|
|
|
pub fn run_async<F, T>(func: F) -> AsyncJob<T>
|
|
where
|
|
F: FnOnce() -> T + Send + 'static,
|
|
T: Send + 'static,
|
|
{
|
|
let (tx, rx) = bounded(1);
|
|
|
|
rayon::spawn(move || {
|
|
let result = func();
|
|
let _ = tx.send(result);
|
|
});
|
|
|
|
AsyncJob { receiver: rx }
|
|
}
|