在结构中保留对 timer::guard 的引用

Retain reference to timer::guard in struct

我正在尝试实现一个跟踪全局滴答的结构。为了重构,我将 timer 移动到结构中,但现在我面临 timer guard 丢失引用的问题,因此计时器被丢弃。我的想法是将守卫添加为结构成员,但我不确定该怎么做。

use timer;
use chrono;
use futures::Future;
use std::{process, thread};
use std::sync::{Arc, Mutex};

struct GlobalTime {
    tick_count: Arc<Mutex<u64>>,
    millis: Arc<Mutex<i64>>,
    timer: timer::Timer,
    guard: timer::Guard,
}

impl GlobalTime {
    fn new() -> GlobalTime {
        GlobalTime {
            tick_count: Arc::new(Mutex::new(0)),
            millis: Arc::new(Mutex::new(200)),
            timer: timer::Timer::new(),
            guard: ???, // what do I do here to init the guard??
        }
    }

    fn tick(&self) {
        *self.guard = {
            let global_tick = self.tick_count.clone();
            self.timer.schedule_repeating(
                chrono::Duration::milliseconds(*self.millis.lock().unwrap()),
                move || {
                    *global_tick.lock().unwrap() += 1;
                    println!("timer callback");
                },
            );
        }
    }
}

鉴于计时器在 GlobalTime 的生命周期内并不总是 运行,guard 并不总是有效的值。我们通常用 Option:

来模拟这个想法
struct GlobalTime {
    tick_count: Arc<Mutex<u64>>,
    millis: Arc<Mutex<i64>>,
    timer: timer::Timer,
    guard: Option<timer::Guard>,
}

这也解决了你的初始值是什么的问题,因为它是 Option::None:

impl GlobalTime {
    fn new() -> GlobalTime {
        GlobalTime {
            tick_count: Arc::new(Mutex::new(0)),
            millis: Arc::new(Mutex::new(200)),
            timer: timer::Timer::new(),
            guard: None,
        }
    }
}

tick方法变为:

fn tick(&mut self) {
    let global_tick = self.tick_count.clone();
    let guard = self.timer.schedule_repeating(
        chrono::Duration::milliseconds(*self.millis.lock().unwrap()),
        move || {
            *global_tick.lock().unwrap() += 1;
            println!("timer callback");
        },
    );
    self.guard = Some(guard);
}

要停止计时器,您只需将保护值设置为 Option::None:

fn stop(&mut self) {
    self.guard = None;
}