Re: Correct API to implement a timer in a real-time thread
Re: Correct API to implement a timer in a real-time thread
- Subject: Re: Correct API to implement a timer in a real-time thread
- From: Christian Brunschen <email@hidden>
- Date: Thu, 5 Jan 2006 15:35:37 +0100 (CET)
On Thu, 5 Jan 2006, Stéphane Letz wrote:
[ ... ] The thing is that when using this kind of functions, i
have to deal with cases where an abnormal latency occur in the system, then
the wait function returns too late, I have to compensate for that for the
next interrupt and so on.
But that's easy - here's some pseudocode:
time_t start = now();
time_t next = start;
time_t interval = // ...
while(true) {
time_t now = now();
while (next < now) { next += interval; }
sleep(next - now);
// do something
}
This will attempt to 'do something' at fixed intervals. Even if there is
latency or an unexpected delay at some point, the next time to wake up
will still be "start + (n * interval)" for soem value of n. If the
unexpected latency exceeds one interval, then an interval will be skipped.
If you need to avoid skipping any invocations - in other words, if such a
latency burst should not result in any invocations being skipped, but
instead in perhaps severl invocations happening as quickly as possible
until the system has caught up - then you can modify the pseudocode above:
time_t start = now();
time_t next = start;
time_t interval = // ...
while(true) {
time_t now = now();
next += interval;
time_t ahead = next - now;
if (ahead > 0) {
sleep(ahead);
}
// do something
}
This will never skip any invocations; but if your system is loaded, or if
your 'do something' processing takes too long, this will end up being
permanently behind its expetcted timer, and start hogging CPU.
[ ... ]
Stephane
Best wishes,
// Christian
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden