-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcancel_nested.rs
More file actions
67 lines (54 loc) · 2.14 KB
/
cancel_nested.rs
File metadata and controls
67 lines (54 loc) · 2.14 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use std::{
sync::{mpsc, Arc},
thread,
time::Duration,
};
use sitrep::{Controller, Event, Progress, State, StdMpscObserver, Task, UpdateEvent};
fn main() {
let (sender, receiver) = mpsc::channel();
let observer = Arc::new(StdMpscObserver::from(sender));
let (parent, controller) = Progress::new(Task::default(), observer);
// The sending end of the progress report:
let worker_handle = thread::spawn(move || {
let worker_handles: Vec<_> = (0..3)
.map(|_| {
let parent = Arc::clone(&parent);
thread::spawn(move || {
let child = Progress::new_with_parent(Task::default(), &parent);
let total = 100;
child.set_total(total);
for completed in 1..=total {
thread::sleep(Duration::from_millis(25));
// Check if the user canceled the task from the controller end of things:
if child.state() == State::Canceled {
println!("Task got canceled by user, aborting.");
break;
}
child.set_completed(completed);
}
})
})
.collect();
for worker_handle in worker_handles {
worker_handle.join().unwrap();
}
});
// The receiving end of the progress report:
let controller_handle = thread::spawn(move || {
while let Ok(event) = receiver.recv() {
let Event::Update(UpdateEvent { id: _ }) = event else {
// For the sake of brevity we'll only handle the update events here:
continue;
};
// The controller is only available as long as
// the corresponding progress is alive, too:
let Some(controller) = controller.upgrade() else {
break;
};
// Cancel the task from the controller end of things:
controller.cancel().ok();
}
});
worker_handle.join().unwrap();
controller_handle.join().unwrap();
}