#object #tracking #pair #controller #track #tracker #keep

object-controller-tracker

跟踪对象-控制器对

1 个不稳定版本

0.1.0 2019年4月7日

#42 in #keep

MIT/Apache

11KB
134 代码行

object-controller-tracker

一个用于跟踪Object-Controller对的crate,其中控制器用于操作对象(例如取消操作),通常来自其他线程。

构建并使用Tracker对象来注册Object-Controller对。当一个Object被丢弃时,Controller会自动注销。可以使用Tracker对象通过其关联的控制器操作所有已注册的对象。

示例


// The object we want to track...
struct Object {
    stop: Arc<AtomicBool>,
    //...
}

// ... and its associated controller.
struct Controller(Arc<AtomicBool>);

impl Object {

    // Create an Object-Controller pair.
    fn new2() -> (Object, Controller) {
        let stop = Arc::new(AtomicBool::new(false));
        let ctl_stop = Arc::clone(&stop);
        (Object { stop }, Controller(ctl_stop))
    }

    // Some method on the object that can be cancelled through the Controller.
    fn do_something(&self) {
        while !self.stop.load(Ordering::SeqCst) {
            println!("Do something.");
            std::thread::sleep(Duration::from_secs(1));
        }
    }
}

impl Controller {
    // Cancel an operation on the Object.
    fn cancel(&self) {
        self.0.store(true, Ordering::SeqCst);
    }
}

fn main() {
    // Create the tracker object.
    let mut tracker = Tracker::new();

    let tracker2 = tracker.clone();
    let thread = std::thread::spawn(move || {
        // Create an Object-Controller pair in some thread.
        let (object, controller) = Object::new2();

        // Register it with the tracker.
        let object = tracker2.track(object, controller);

        // Do some work with the Object.
        object.do_something();
    });

    std::thread::sleep(Duration::from_secs(5));

    // Cancel all registered Object operations.
    tracker.for_each(|r| r.cancel());

    thread.join().unwrap();
}

许可:MIT/Apache2.0

无运行时依赖