Permalink
Browse files

Add solution

  • Loading branch information...
snoyberg committed Nov 25, 2018
1 parent 03c5b90 commit 1c58bf4df946763f5f9f0773235e975968260ba9
Showing with 20 additions and 1 deletion.
  1. +2 −0 src/future.rs
  2. +18 −1 src/interval.rs
@@ -22,6 +22,8 @@ impl Future for IntervalFuture {
fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
let curr = self.interval.get_counter();
if curr == self.last {
let task = futures::task::current();
self.interval.set_task(task);
Ok(Async::NotReady)
} else {
self.last = curr;
@@ -1,12 +1,14 @@
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::thread::{sleep, spawn};
use std::time::Duration;
use futures::task::Task;
#[derive(Clone)]
pub struct Interval {
counter: Arc<AtomicUsize>,
still_running: Arc<AtomicBool>,
task: Arc<Mutex<Option<Task>>>,
}
impl Drop for Interval {
@@ -26,22 +28,37 @@ impl Interval {
let still_running = Arc::new(AtomicBool::new(true));
let still_running_clone = still_running.clone();
let task: Arc<Mutex<Option<Task>>> = Arc::new(Mutex::new(None));
let task_clone = task.clone();
spawn(move || {
println!("Interval thread launched");
while still_running_clone.load(Ordering::SeqCst) {
sleep(duration);
let old = counter_clone.fetch_add(1, Ordering::SeqCst);
println!("Interval thread still alive, value was: {}", old);
let task = task_clone.lock().unwrap();
match *task {
None => (),
Some(ref task) => task.notify(),
};
}
});
Interval {
counter,
still_running,
task,
}
}
pub fn get_counter(&self) -> usize {
self.counter.load(Ordering::SeqCst)
}
pub fn set_task(&mut self, task: Task) {
let mut guard = self.task.lock().unwrap();
*guard = Some(task);
}
}

0 comments on commit 1c58bf4

Please sign in to comment.