Implementing a timer using threads

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Jan 30 13:07:26 PST 2007


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();
}
---


More information about the Digitalmars-d-learn mailing list