use std::io;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
use super::instant::*;
#[derive(Debug)]
pub struct Updater {
running: Arc<AtomicBool>,
th: Option<thread::JoinHandle<()>>,
}
impl Updater {
pub fn new() -> Result<Self, io::Error> {
let running = Arc::new(AtomicBool::new(true));
let running_pass = running.clone();
let th: thread::JoinHandle<()> = thread::Builder::new()
.name("ascending_time_updater".to_string())
.spawn(move || {
while running_pass.load(Ordering::Relaxed) {
thread::sleep(Duration::from_millis(0));
Instant::update();
}
})?;
Instant::update();
Ok(Updater {
running,
th: Some(th),
})
}
pub fn stop(mut self) -> Result<(), io::Error> {
self.running.store(false, Ordering::Relaxed);
self.th
.take()
.expect("The Thread was already unloaded.")
.join()
.map_err(|_| {
io::Error::other("failed to properly stop the updater")
})
}
}
impl Drop for Updater {
fn drop(&mut self) {
self.running.store(false, Ordering::Relaxed);
}
}