forked from SpaceManiac/SpacemanDMM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks.rs
More file actions
44 lines (37 loc) · 1.07 KB
/
tasks.rs
File metadata and controls
44 lines (37 loc) · 1.07 KB
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
//! Helper for running background tasks.
use std::sync::mpsc::{channel, Receiver, TryRecvError};
use std::thread;
pub type Err = Box<dyn std::error::Error + Send + Sync>;
pub struct Task<R> {
name: String,
rx: Receiver<Result<R, Err>>,
}
impl<R: Send + 'static> Task<R> {
pub fn spawn<S: Into<String>, F: FnOnce() -> Result<R, Err> + Send + 'static>(name: S, f: F) -> Self {
Task {
name: name.into(),
rx: spawn(f),
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn poll<F: FnMut(Result<R, Err>)>(&self, mut f: F) -> bool {
match self.rx.try_recv() {
Ok(v) => {
f(v);
true
}
Err(TryRecvError::Empty) => true,
Err(TryRecvError::Disconnected) => false,
}
}
}
pub fn spawn<R: Send + 'static, F: FnOnce() -> Result<R, Err> + Send + 'static>(f: F) -> Receiver<Result<R, Err>> {
let (tx, rx) = channel();
thread::spawn(move || {
// TODO: catch unwind
let _ = tx.send(f());
});
rx
}