View mode: basic / threaded / horizontal-split · Log in · Help
January 30, 2007
Re: Implementing a timer using threads
Reply to Frits,

> BCS wrote:
> 
>> while(NothingToDo())
>> thisThread.MarkTime();
>
> Couldn't you just do something like:
> -----
> time_t nextEvent = currentTime() + interval;
> time_t now;
> while (true) {
> while ((now = currentTime()) < nextEvent)
> sleep(nextEvent - now);        // or msleep, if you prefer
> nextEvent += interval;
> action();
> }
> -----
> (where time_t is some type suitable for measuring time)
> That should sleep until it's time, right?
> 

That would work if the end condition is a clock time. It's not quite the 
same problem but what about if you are waiting for some logical condition?
January 30, 2007
Re: Implementing a timer using threads
BCS wrote:
> Reply to Frits,
> 
>> BCS wrote:
>>
>>> while(NothingToDo())
>>> thisThread.MarkTime();
>>
>> Couldn't you just do something like:
>> -----
>> time_t nextEvent = currentTime() + interval;
>> time_t now;
>> while (true) {
>> while ((now = currentTime()) < nextEvent)
>> sleep(nextEvent - now);        // or msleep, if you prefer
>> nextEvent += interval;
>> action();
>> }
>> -----
>> (where time_t is some type suitable for measuring time)
>> That should sleep until it's time, right?
>>
> 
> That would work if the end condition is a clock time. It's not quite the 
> same problem but what about if you are waiting for some logical condition?

Then you pick a reasonable poll interval and do something like this:
---
time_t nextCheck = currentTime();
while(true) {
    while (!condition()) {
        nextCheck += poll_interval;
        sleep(nextCheck - currentTime());
    }
    action();
}
---
January 30, 2007
Re: Implementing a timer using threads
Reply to Frits,

> Then you pick a reasonable poll interval and do something like this:
[snip]

Man, wouldn't it be better if the OS writers would just put in a proper yield?
Next ›   Last »
1 2
Top | Discussion index | About this forum | D home