rust/src/libnative/io/timer_win32.rs

204 lines
6.5 KiB
Rust
Raw Normal View History

Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Timers based on win32 WaitableTimers
//!
//! This implementation is meant to be used solely on windows. As with other
//! implementations, there is a worker thread which is doing all the waiting on
//! a large number of timers for all active timers in the system. This worker
//! thread uses the select() equivalent, WaitForMultipleObjects. One of the
//! objects being waited on is a signal into the worker thread to notify that
//! the incoming channel should be looked at.
//!
//! Other than that, the implementation is pretty straightforward in terms of
//! the other two implementations of timers with nothing *that* new showing up.
use std::comm::Data;
use std::libc;
use std::ptr;
use std::rt::rtio;
use io::timer_helper;
use io::IoResult;
pub struct Timer {
priv obj: libc::HANDLE,
priv on_worker: bool,
}
pub enum Req {
NewTimer(libc::HANDLE, Chan<()>, bool),
RemoveTimer(libc::HANDLE, Chan<()>),
Shutdown,
}
fn helper(input: libc::HANDLE, messages: Port<Req>) {
let mut objs = ~[input];
let mut chans = ~[];
'outer: loop {
let idx = unsafe {
imp::WaitForMultipleObjects(objs.len() as libc::DWORD,
objs.as_ptr(),
0 as libc::BOOL,
libc::INFINITE)
};
if idx == 0 {
loop {
match messages.try_recv() {
Data(NewTimer(obj, c, one)) => {
objs.push(obj);
chans.push((c, one));
}
Data(RemoveTimer(obj, c)) => {
c.send(());
match objs.iter().position(|&o| o == obj) {
Some(i) => {
drop(objs.remove(i));
drop(chans.remove(i - 1));
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
}
None => {}
}
}
Data(Shutdown) => {
assert_eq!(objs.len(), 1);
assert_eq!(chans.len(), 0);
break 'outer;
}
_ => break
}
}
} else {
let remove = {
match &chans[idx - 1] {
&(ref c, oneshot) => !c.try_send(()) || oneshot
}
};
if remove {
drop(objs.remove(idx as uint));
drop(chans.remove(idx as uint - 1));
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
}
}
}
}
impl Timer {
pub fn new() -> IoResult<Timer> {
timer_helper::boot(helper);
let obj = unsafe {
imp::CreateWaitableTimerA(ptr::mut_null(), 0, ptr::null())
};
if obj.is_null() {
Err(super::last_error())
} else {
Ok(Timer { obj: obj, on_worker: false, })
}
}
pub fn sleep(ms: u64) {
use std::rt::rtio::RtioTimer;
let mut t = Timer::new().ok().expect("must allocate a timer!");
t.sleep(ms);
}
fn remove(&mut self) {
if !self.on_worker { return }
let (p, c) = Chan::new();
timer_helper::send(RemoveTimer(self.obj, c));
p.recv();
self.on_worker = false;
}
}
impl rtio::RtioTimer for Timer {
fn sleep(&mut self, msecs: u64) {
self.remove();
// there are 10^6 nanoseconds in a millisecond, and the parameter is in
// 100ns intervals, so we multiply by 10^4.
let due = -(msecs * 10000) as libc::LARGE_INTEGER;
assert_eq!(unsafe {
imp::SetWaitableTimer(self.obj, &due, 0, ptr::null(),
ptr::mut_null(), 0)
}, 1);
let _ = unsafe { imp::WaitForSingleObject(self.obj, libc::INFINITE) };
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
}
fn oneshot(&mut self, msecs: u64) -> Port<()> {
self.remove();
let (p, c) = Chan::new();
// see above for the calculation
let due = -(msecs * 10000) as libc::LARGE_INTEGER;
assert_eq!(unsafe {
imp::SetWaitableTimer(self.obj, &due, 0, ptr::null(),
ptr::mut_null(), 0)
}, 1);
timer_helper::send(NewTimer(self.obj, c, true));
self.on_worker = true;
return p;
}
fn period(&mut self, msecs: u64) -> Port<()> {
self.remove();
let (p, c) = Chan::new();
// see above for the calculation
let due = -(msecs * 10000) as libc::LARGE_INTEGER;
assert_eq!(unsafe {
imp::SetWaitableTimer(self.obj, &due, msecs as libc::LONG,
ptr::null(), ptr::mut_null(), 0)
}, 1);
timer_helper::send(NewTimer(self.obj, c, false));
self.on_worker = true;
return p;
}
}
impl Drop for Timer {
fn drop(&mut self) {
self.remove();
assert!(unsafe { libc::CloseHandle(self.obj) != 0 });
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
}
}
mod imp {
use std::libc::{LPSECURITY_ATTRIBUTES, BOOL, LPCSTR, HANDLE, LARGE_INTEGER,
LONG, LPVOID, DWORD, c_void};
pub type PTIMERAPCROUTINE = *c_void;
extern "system" {
pub fn CreateWaitableTimerA(lpTimerAttributes: LPSECURITY_ATTRIBUTES,
bManualReset: BOOL,
lpTimerName: LPCSTR) -> HANDLE;
pub fn SetWaitableTimer(hTimer: HANDLE,
pDueTime: *LARGE_INTEGER,
lPeriod: LONG,
pfnCompletionRoutine: PTIMERAPCROUTINE,
lpArgToCompletionRoutine: LPVOID,
fResume: BOOL) -> BOOL;
pub fn WaitForMultipleObjects(nCount: DWORD,
lpHandles: *HANDLE,
bWaitAll: BOOL,
dwMilliseconds: DWORD) -> DWORD;
pub fn WaitForSingleObject(hHandle: HANDLE,
dwMilliseconds: DWORD) -> DWORD;
}
}