aboutsummaryrefslogtreecommitdiffstats
path: root/src/timers/timer.rs
blob: 5426c79b07c5cec23a726ff45b46feb4cd91fadd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use ferris::*;
use spin;
use std::collections::HashMap;
use std::mem;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Weak};
use std::thread;
use std::time::{Duration, Instant};
use std::u64;

extern crate test;

type TimerID = u64;
type TimerKey = (u64, usize);
type Callback = (Arc<AtomicBool>, Box<dyn Fn() -> () + Send + 'static>);

const ACCURACY: Duration = Duration::from_millis(100);
const OFFSET: Duration = Duration::from_millis(1000);

struct RunnerInner {
    keys: AtomicU64,
    wheel: spin::Mutex<CopyWheel<TimerKey>>,
    running: AtomicBool,
    callback: spin::Mutex<HashMap<TimerID, Callback>>,
}

pub struct Timer {
    pending: Arc<AtomicBool>,
    runner: Weak<RunnerInner>,
    id: u64,
    cnt: AtomicUsize,
}

pub struct Runner(Arc<RunnerInner>, Option<thread::JoinHandle<()>>);

impl Runner {
    pub fn new() -> Self {
        let inner = Arc::new(RunnerInner {
            running: AtomicBool::new(true),
            callback: spin::Mutex::new(HashMap::new()),
            keys: AtomicU64::new(0),
            wheel: spin::Mutex::new(CopyWheel::<TimerKey>::new(vec![
                Resolution::HundredMs,
                Resolution::Sec,
                Resolution::Min,
            ])),
        });

        // start runner thread
        let handle = {
            let inner = inner.clone();
            thread::spawn(move || {
                let mut next = Instant::now() + ACCURACY;
                while inner.running.load(Ordering::Acquire) {
                    // sleep for 1 tick
                    let now = Instant::now();
                    if next > now {
                        thread::sleep(next - now);
                    }
                    next = now + ACCURACY;

                    // extract expired events
                    let expired = inner.wheel.lock().expire();

                    // handle expired events
                    for key in &expired {
                        if let Some((pending, callback)) = inner.callback.lock().get(&key.0) {
                            if pending.swap(false, Ordering::SeqCst) {
                                callback();
                            }
                        } else {
                            unreachable!()
                        };
                    }
                }
            })
        };

        Runner(inner, Some(handle))
    }

    pub fn timer(&self, callback: Box<dyn Fn() -> () + Send + 'static>) -> Timer {
        let id = self.0.keys.fetch_add(1, Ordering::Relaxed);
        let pending = Arc::new(AtomicBool::new(false));

        assert!(id < u64::MAX, "wrapping of ids");

        self.0
            .callback
            .lock()
            .insert(id, (pending.clone(), callback));

        Timer {
            id,
            pending: pending,
            runner: Arc::downgrade(&self.0.clone()),
            cnt: AtomicUsize::new(0),
        }
    }
}

impl Timer {
    pub fn reset(&self, duration: Duration) {
        if let Some(runner) = self.runner.upgrade() {
            let mut wheel = runner.wheel.lock();
            let cnt = self.cnt.fetch_add(1, Ordering::SeqCst);
            self.pending.store(true, Ordering::SeqCst);
            wheel.stop((self.id, cnt));
            wheel.start((self.id, cnt + 1), duration - OFFSET);
        }
    }

    pub fn start(&self, duration: Duration) {
        if self.pending.load(Ordering::Acquire) {
            return;
        }

        if let Some(runner) = self.runner.upgrade() {
            let mut wheel = runner.wheel.lock();
            if !self.pending.swap(true, Ordering::SeqCst) {
                let cnt = self.cnt.fetch_add(1, Ordering::SeqCst);
                wheel.start((self.id, cnt + 1), duration - OFFSET);
            }
        }
    }

    pub fn stop(&self) {
        if self.pending.load(Ordering::Acquire) {
            if let Some(runner) = self.runner.upgrade() {
                let mut wheel = runner.wheel.lock();
                if self.pending.swap(false, Ordering::SeqCst) {
                    let cnt = self.cnt.load(Ordering::SeqCst);
                    wheel.stop((self.id, cnt));
                }
            }
        }
    }
}

impl Drop for Runner {
    fn drop(&mut self) {
        self.0.running.store(false, Ordering::SeqCst);
        if let Some(handle) = mem::replace(&mut self.1, None) {
            handle.join().unwrap();
        }
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        self.stop();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test::Bencher;

    #[bench]
    fn bench_reset(b: &mut Bencher) {
        let runner = Runner::new();
        let timer = runner.timer(Box::new(|| {}));
        b.iter(|| timer.reset(Duration::from_millis(1000)));
    }

    #[bench]
    fn bench_start(b: &mut Bencher) {
        let runner = Runner::new();
        let timer = runner.timer(Box::new(|| {}));
        b.iter(|| timer.start(Duration::from_millis(1000)));
    }
}