Module native::io::timer[src]
Timers for non-linux/non-windows OSes
This module implements timers with a worker thread, select(), and a lot of witchcraft that turns out to be horribly inaccurate timers. The unfortunate part is that I'm at a loss of what else to do one these OSes. This is also why linux has a specialized timerfd implementation and windows has its own implementation (they're more accurate than this one).
The basic idea is that there is a worker thread that's communicated to via a channel and a pipe, the pipe is used by the worker thread in a select() syscall with a timeout. The timeout is the "next timer timeout" while the channel is used to send data over to the worker thread.
Whenever the call to select() times out, then a channel receives a message. Whenever the call returns that the file descriptor has information, then the channel from timers is drained, enqueuing all incoming requests.
The actual implementation of the helper thread is a sorted array of timers in terms of target firing date. The target is the absolute time at which the timer should fire. Timers are then re-enqueued after a firing if the repeat boolean is set.
Naturally, all this logic of adding times and keeping track of relative/absolute time is a little lossy and not quite exact. I've done the best I could to reduce the amount of calls to 'now()', but there's likely still inaccuracies trickling in here and there.
One of the tricky parts of this implementation is that whenever a timer is acted upon, it must cancel whatever the previous action was (if one is active) in order to act like the other implementations of this timer. In order to do this, the timer's inner pointer is transferred to the worker thread. Whenever the timer is modified, it first takes ownership back from the worker thread in order to modify the same data structure. This has the side effect of "cancelling" the previous requests while allowing a re-enqueuing later on.
Note that all time units in this file are in milliseconds.
Structs
| Timer |
Enums
| Req |
Functions
| now |