example2/
example2.rs

1extern crate object_controller_tracker;
2
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::Arc;
5use std::time::Duration;
6
7use object_controller_tracker::*;
8
9struct Object {
10    id: u32,
11    stop: Arc<AtomicBool>,
12    //...
13}
14
15struct Controller {
16    id: u32,
17    stop: Arc<AtomicBool>,
18}
19
20impl Object {
21    fn new2(id: u32) -> (Object, Controller) {
22        let stop = Arc::new(AtomicBool::new(false));
23        let remote_stop = Arc::clone(&stop);
24        (
25            Object { id, stop },
26            Controller {
27                id,
28                stop: remote_stop,
29            },
30        )
31    }
32
33    fn do_something(&self) {
34        for _ in 0..(self.id * 2) {
35            if self.stop.load(Ordering::SeqCst) {
36                break;
37            }
38            println!("Do something {}.", self.id);
39            std::thread::sleep(Duration::from_secs(1));
40        }
41    }
42}
43
44impl Controller {
45    fn cancel(&self) {
46        println!("Cancel {}.", self.id);
47        self.stop.store(true, Ordering::SeqCst);
48    }
49}
50
51fn main() {
52    let mut tracker = Tracker::new();
53
54    let mut threads = Vec::new();
55
56    for i in 1..5 {
57        let tracker2 = tracker.clone();
58        let thread = std::thread::spawn(move || {
59            let (object, controller) = Object::new2(i);
60            let object = tracker2.track(object, controller);
61
62            object.do_something();
63
64            println!("Quit {}", i);
65        });
66        threads.push(thread);
67    }
68
69    std::thread::sleep(Duration::from_secs(5));
70
71    tracker.for_each(|r| r.cancel());
72
73    for thread in threads {
74        thread.join().unwrap();
75    }
76}