Re: Correct API to implement a timer in a real-time thread
site_archiver@lists.apple.com Delivered-To: Darwin-dev@lists.apple.com On Thu, 5 Jan 2006, Stéphane Letz wrote: 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 } 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 } [ ... ] Best wishes, // Christian _______________________________________________ Do not post admin requests to the list. They will be ignored. Darwin-dev mailing list (Darwin-dev@lists.apple.com) Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/darwin-dev/site_archiver%40lists.appl... This email sent to site_archiver@lists.apple.com [ ... ] 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. 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: 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
participants (1)
-
Christian Brunschen