promised fn

This commit is contained in:
JMARyA 2025-03-07 21:20:25 +01:00
parent e3393f1e09
commit 0c190df5d7
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
4 changed files with 39 additions and 1 deletions

View file

@ -7,6 +7,15 @@ pub struct JobDispatcher<T: Send + 'static, V: Send + 'static> {
sender: Sender<JobOrder<T, V>>,
}
pub struct JobResult<V>(std::sync::mpsc::Receiver<V>);
impl<V> JobResult<V> {
/// Wait for the Result of a Job.
pub fn wait(self) -> V {
self.0.recv().unwrap()
}
}
impl<T: Send + 'static, V: Send + 'static> JobDispatcher<T, V> {
/// Creates a new instance of `JobDispatcher` and returns a tuple that contains it and a receiver end for `JobOrder`s.
/// # Example:
@ -48,6 +57,15 @@ impl<T: Send + 'static, V: Send + 'static> JobDispatcher<T, V> {
rx.recv().unwrap()
}
pub fn send_async(&self, param: T) -> JobResult<V> {
let (tx, rx) = mpsc::channel();
let job_order = JobOrder::new(param, move |ret| {
tx.send(ret).unwrap();
});
self.sender.send(job_order).unwrap();
JobResult(rx)
}
/// Sends a job of type `T` to the job dispatcher and waits for its result of type `V`.
/// Returns `Some(V)` when the job returns an result, `None` if somehow nothing was returned or the internal `Mutex` is poisoned.
pub fn try_send(&self, param: T) -> Option<V> {