]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/timer.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / libstd / sys / unix / timer.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Timers for non-Linux/non-Windows OSes
12 //!
13 //! This module implements timers with a worker thread, select(), and a lot of
14 //! witchcraft that turns out to be horribly inaccurate timers. The unfortunate
15 //! part is that I'm at a loss of what else to do one these OSes. This is also
16 //! why Linux has a specialized timerfd implementation and windows has its own
17 //! implementation (they're more accurate than this one).
18 //!
19 //! The basic idea is that there is a worker thread that's communicated to via a
20 //! channel and a pipe, the pipe is used by the worker thread in a select()
21 //! syscall with a timeout. The timeout is the "next timer timeout" while the
22 //! channel is used to send data over to the worker thread.
23 //!
24 //! Whenever the call to select() times out, then a channel receives a message.
25 //! Whenever the call returns that the file descriptor has information, then the
26 //! channel from timers is drained, enqueuing all incoming requests.
27 //!
28 //! The actual implementation of the helper thread is a sorted array of
29 //! timers in terms of target firing date. The target is the absolute time at
30 //! which the timer should fire. Timers are then re-enqueued after a firing if
31 //! the repeat boolean is set.
32 //!
33 //! Naturally, all this logic of adding times and keeping track of
34 //! relative/absolute time is a little lossy and not quite exact. I've done the
35 //! best I could to reduce the amount of calls to 'now()', but there's likely
36 //! still inaccuracies trickling in here and there.
37 //!
38 //! One of the tricky parts of this implementation is that whenever a timer is
39 //! acted upon, it must cancel whatever the previous action was (if one is
40 //! active) in order to act like the other implementations of this timer. In
41 //! order to do this, the timer's inner pointer is transferred to the worker
42 //! thread. Whenever the timer is modified, it first takes ownership back from
43 //! the worker thread in order to modify the same data structure. This has the
44 //! side effect of "cancelling" the previous requests while allowing a
45 //! re-enqueuing later on.
46 //!
47 //! Note that all time units in this file are in *milliseconds*.
48
49 use prelude::v1::*;
50 use self::Req::*;
51
52 use io::IoResult;
53 use libc;
54 use mem;
55 use os;
56 use ptr;
57 use sync::atomic::{mod, Ordering};
58 use sync::mpsc::{channel, Sender, Receiver, TryRecvError};
59 use sys::c;
60 use sys::fs::FileDesc;
61 use sys_common::helper_thread::Helper;
62
63 helper_init! { static HELPER: Helper<Req> }
64
65 pub trait Callback {
66     fn call(&mut self);
67 }
68
69 pub struct Timer {
70     id: uint,
71     inner: Option<Box<Inner>>,
72 }
73
74 pub struct Inner {
75     cb: Option<Box<Callback + Send>>,
76     interval: u64,
77     repeat: bool,
78     target: u64,
79     id: uint,
80 }
81
82 pub enum Req {
83     // Add a new timer to the helper thread.
84     NewTimer(Box<Inner>),
85
86     // Remove a timer based on its id and then send it back on the channel
87     // provided
88     RemoveTimer(uint, Sender<Box<Inner>>),
89 }
90
91 // returns the current time (in milliseconds)
92 pub fn now() -> u64 {
93     unsafe {
94         let mut now: libc::timeval = mem::zeroed();
95         assert_eq!(c::gettimeofday(&mut now, ptr::null_mut()), 0);
96         return (now.tv_sec as u64) * 1000 + (now.tv_usec as u64) / 1000;
97     }
98 }
99
100 fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
101     let mut set: c::fd_set = unsafe { mem::zeroed() };
102
103     let mut fd = FileDesc::new(input, true);
104     let mut timeout: libc::timeval = unsafe { mem::zeroed() };
105
106     // active timers are those which are able to be selected upon (and it's a
107     // sorted list, and dead timers are those which have expired, but ownership
108     // hasn't yet been transferred back to the timer itself.
109     let mut active: Vec<Box<Inner>> = vec![];
110     let mut dead = vec![];
111
112     // inserts a timer into an array of timers (sorted by firing time)
113     fn insert(t: Box<Inner>, active: &mut Vec<Box<Inner>>) {
114         match active.iter().position(|tm| tm.target > t.target) {
115             Some(pos) => { active.insert(pos, t); }
116             None => { active.push(t); }
117         }
118     }
119
120     // signals the first requests in the queue, possible re-enqueueing it.
121     fn signal(active: &mut Vec<Box<Inner>>,
122               dead: &mut Vec<(uint, Box<Inner>)>) {
123         if active.is_empty() { return }
124
125         let mut timer = active.remove(0);
126         let mut cb = timer.cb.take().unwrap();
127         cb.call();
128         if timer.repeat {
129             timer.cb = Some(cb);
130             timer.target += timer.interval;
131             insert(timer, active);
132         } else {
133             dead.push((timer.id, timer));
134         }
135     }
136
137     'outer: loop {
138         let timeout = if active.len() == 0 {
139             // Empty array? no timeout (wait forever for the next request)
140             ptr::null_mut()
141         } else {
142             let now = now();
143             // If this request has already expired, then signal it and go
144             // through another iteration
145             if active[0].target <= now {
146                 signal(&mut active, &mut dead);
147                 continue;
148             }
149
150             // The actual timeout listed in the requests array is an
151             // absolute date, so here we translate the absolute time to a
152             // relative time.
153             let tm = active[0].target - now;
154             timeout.tv_sec = (tm / 1000) as libc::time_t;
155             timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t;
156             &mut timeout as *mut libc::timeval
157         };
158
159         c::fd_set(&mut set, input);
160         match unsafe {
161             c::select(input + 1, &mut set, ptr::null_mut(),
162                       ptr::null_mut(), timeout)
163         } {
164             // timed out
165             0 => signal(&mut active, &mut dead),
166
167             // file descriptor write woke us up, we've got some new requests
168             1 => {
169                 loop {
170                     match messages.try_recv() {
171                         Err(TryRecvError::Disconnected) => {
172                             assert!(active.len() == 0);
173                             break 'outer;
174                         }
175
176                         Ok(NewTimer(timer)) => insert(timer, &mut active),
177
178                         Ok(RemoveTimer(id, ack)) => {
179                             match dead.iter().position(|&(i, _)| id == i) {
180                                 Some(i) => {
181                                     let (_, i) = dead.remove(i);
182                                     ack.send(i).unwrap();
183                                     continue
184                                 }
185                                 None => {}
186                             }
187                             let i = active.iter().position(|i| i.id == id);
188                             let i = i.expect("no timer found");
189                             let t = active.remove(i);
190                             ack.send(t).unwrap();
191                         }
192                         Err(..) => break
193                     }
194                 }
195
196                 // drain the file descriptor
197                 let mut buf = [0];
198                 assert_eq!(fd.read(&mut buf).ok().unwrap(), 1);
199             }
200
201             -1 if os::errno() == libc::EINTR as uint => {}
202             n => panic!("helper thread failed in select() with error: {} ({})",
203                        n, os::last_os_error())
204         }
205     }
206 }
207
208 impl Timer {
209     pub fn new() -> IoResult<Timer> {
210         // See notes above regarding using int return value
211         // instead of ()
212         HELPER.boot(|| {}, helper);
213
214         static ID: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
215         let id = ID.fetch_add(1, Ordering::Relaxed);
216         Ok(Timer {
217             id: id,
218             inner: Some(box Inner {
219                 cb: None,
220                 interval: 0,
221                 target: 0,
222                 repeat: false,
223                 id: id,
224             })
225         })
226     }
227
228     pub fn sleep(&mut self, ms: u64) {
229         let mut inner = self.inner();
230         inner.cb = None; // cancel any previous request
231         self.inner = Some(inner);
232
233         let mut to_sleep = libc::timespec {
234             tv_sec: (ms / 1000) as libc::time_t,
235             tv_nsec: ((ms % 1000) * 1000000) as libc::c_long,
236         };
237         while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 {
238             if os::errno() as int != libc::EINTR as int {
239                 panic!("failed to sleep, but not because of EINTR?");
240             }
241         }
242     }
243
244     pub fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>) {
245         let now = now();
246         let mut inner = self.inner();
247
248         inner.repeat = false;
249         inner.cb = Some(cb);
250         inner.interval = msecs;
251         inner.target = now + msecs;
252
253         HELPER.send(NewTimer(inner));
254     }
255
256     pub fn period(&mut self, msecs: u64, cb: Box<Callback + Send>) {
257         let now = now();
258         let mut inner = self.inner();
259
260         inner.repeat = true;
261         inner.cb = Some(cb);
262         inner.interval = msecs;
263         inner.target = now + msecs;
264
265         HELPER.send(NewTimer(inner));
266     }
267
268     fn inner(&mut self) -> Box<Inner> {
269         match self.inner.take() {
270             Some(i) => i,
271             None => {
272                 let (tx, rx) = channel();
273                 HELPER.send(RemoveTimer(self.id, tx));
274                 rx.recv().unwrap()
275             }
276         }
277     }
278 }
279
280 impl Drop for Timer {
281     fn drop(&mut self) {
282         self.inner = Some(self.inner());
283     }
284 }