我正在尝试实现一个跟踪全局刻度的结构。为了重构,我将 移动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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句