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.
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.
11 //! Timers based on Windows WaitableTimers
13 //! This implementation is meant to be used solely on windows. As with other
14 //! implementations, there is a worker thread which is doing all the waiting on
15 //! a large number of timers for all active timers in the system. This worker
16 //! thread uses the select() equivalent, WaitForMultipleObjects. One of the
17 //! objects being waited on is a signal into the worker thread to notify that
18 //! the incoming channel should be looked at.
20 //! Other than that, the implementation is pretty straightforward in terms of
21 //! the other two implementations of timers with nothing *that* new showing up.
30 use sync::mpsc::{channel, Sender, Receiver, TryRecvError};
32 use sys::fs::FileDesc;
33 use sys_common::helper_thread::Helper;
35 helper_init! { static HELPER: Helper<Req> }
47 NewTimer(libc::HANDLE, Box<Callback + Send>, bool),
48 RemoveTimer(libc::HANDLE, Sender<()>),
51 unsafe impl Send for Req {}
54 fn helper(input: libc::HANDLE, messages: Receiver<Req>, _: ()) {
55 let mut objs = vec![input];
56 let mut chans = vec![];
60 imp::WaitForMultipleObjects(objs.len() as libc::DWORD,
68 match messages.try_recv() {
69 Ok(NewTimer(obj, c, one)) => {
73 Ok(RemoveTimer(obj, c)) => {
75 match objs.iter().position(|&o| o == obj) {
78 drop(chans.remove(i - 1));
83 Err(TryRecvError::Disconnected) => {
84 assert_eq!(objs.len(), 1);
85 assert_eq!(chans.len(), 0);
93 match &mut chans[idx as uint - 1] {
94 &mut (ref mut c, oneshot) => { c.call(); oneshot }
98 drop(objs.remove(idx as uint));
99 drop(chans.remove(idx as uint - 1));
105 // returns the current time (in milliseconds)
106 pub fn now() -> u64 {
107 let mut ticks_per_s = 0;
108 assert_eq!(unsafe { libc::QueryPerformanceFrequency(&mut ticks_per_s) }, 1);
109 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
111 assert_eq!(unsafe { libc::QueryPerformanceCounter(&mut ticks) }, 1);
113 return (ticks as u64 * 1000) / (ticks_per_s as u64);
117 pub fn new() -> IoResult<Timer> {
118 HELPER.boot(|| {}, helper);
121 imp::CreateWaitableTimerA(ptr::null_mut(), 0, ptr::null())
124 Err(super::last_error())
126 Ok(Timer { obj: obj, on_worker: false, })
130 fn remove(&mut self) {
131 if !self.on_worker { return }
133 let (tx, rx) = channel();
134 HELPER.send(RemoveTimer(self.obj, tx));
137 self.on_worker = false;
140 pub fn sleep(&mut self, msecs: u64) {
143 // there are 10^6 nanoseconds in a millisecond, and the parameter is in
144 // 100ns intervals, so we multiply by 10^4.
145 let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER;
147 imp::SetWaitableTimer(self.obj, &due, 0, ptr::null_mut(),
151 let _ = unsafe { imp::WaitForSingleObject(self.obj, libc::INFINITE) };
154 pub fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>) {
157 // see above for the calculation
158 let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER;
160 imp::SetWaitableTimer(self.obj, &due, 0, ptr::null_mut(),
164 HELPER.send(NewTimer(self.obj, cb, true));
165 self.on_worker = true;
168 pub fn period(&mut self, msecs: u64, cb: Box<Callback + Send>) {
171 // see above for the calculation
172 let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER;
174 imp::SetWaitableTimer(self.obj, &due, msecs as libc::LONG,
175 ptr::null_mut(), ptr::null_mut(), 0)
178 HELPER.send(NewTimer(self.obj, cb, false));
179 self.on_worker = true;
183 impl Drop for Timer {
186 assert!(unsafe { libc::CloseHandle(self.obj) != 0 });
191 use libc::{LPSECURITY_ATTRIBUTES, BOOL, LPCSTR, HANDLE, LARGE_INTEGER,
192 LONG, LPVOID, DWORD, c_void};
194 pub type PTIMERAPCROUTINE = *mut c_void;
197 pub fn CreateWaitableTimerA(lpTimerAttributes: LPSECURITY_ATTRIBUTES,
199 lpTimerName: LPCSTR) -> HANDLE;
200 pub fn SetWaitableTimer(hTimer: HANDLE,
201 pDueTime: *const LARGE_INTEGER,
203 pfnCompletionRoutine: PTIMERAPCROUTINE,
204 lpArgToCompletionRoutine: LPVOID,
205 fResume: BOOL) -> BOOL;
206 pub fn WaitForMultipleObjects(nCount: DWORD,
207 lpHandles: *const HANDLE,
209 dwMilliseconds: DWORD) -> DWORD;
210 pub fn WaitForSingleObject(hHandle: HANDLE,
211 dwMilliseconds: DWORD) -> DWORD;