Implementing a timer using threads

BCS BCS at pathlink.com
Tue Jan 30 09:06:48 PST 2007


Max Samukha wrote:
> On Mon, 29 Jan 2007 10:55:37 -0800, BCS <BCS at pathlink.com> wrote:
> 
> 
>>Dennis Kempin wrote:
>>
>>>Hi,
>>>
>>>i just started to learn D (have been using c++ or java up to now) and am
>>>wondering how to implement some kind of timer, a thread that calls a
>>>delegate every n seconds.
>>>This was my first idea (without flags for stopping the timer etc):
>>>
>>>class Timer: Thread
>>>{
>>>        int run()
>>>        {
>>>                while(true)
>>>                {
>>>                        this.wait(1000); // wait one second
>>>                        writefln("one second passed");
>>>                }
>>>                return 0;
>>>        }
>>>}
>>>
>>>But writefln never gets executed, because this.wait is used to wait for
>>>other threads than the current one. Is there any other way to get let
>>>Thread sleep for some seconds (I know that there is a Sleep function for
>>>Win32, but a platform independend way would be very great).
>>>
>>>regards
>>>Dennis
>>
>>I'd try something with Thread.yield and a time check.
>>
>>Example (insert your favorite time API)
>>
>>class Timer : Thread
>>{
>>  run()
>>  {
>>    auto next = CurrentTime()+inc;
>>    while(running)
>>    {
>>      auto now = CurrentTime();
>>      if(now > next)
>>      {
>>        dg();
>>        next += inc;
>>      }
>>      else
>>        this.yield();
>>    }
>>  }
>>}
> 
> 
> Be careful about Thread.yield under Windows. It calls Sleep(0) that
> won't yield to a thread of a lower priority. In case of the proposed
> timer this is not a problem except it will use 100% of CPU and won't
> let any lower priority thread run but if you use something like a spin
> lock waiting for a lower priority thread to release it, the lock will
> never be released. 

Ouch, I hadn't head of that.

 > You could use Sleep(1) or SwitchToThread() on
> single processor systems. And you should use 'rep nop' for
> hyperthreaded CPUs.
> 
> A platform independent way to put a thread to sleep using Phobos:
> import std.c.time;
> 
> sleep(1);// secs
> msleep(1000); millisecs
> http://www.digitalmars.com/d/archives/digitalmars/D/29144.html
> 
>  

However that gives the problem of not accounting for the run time of the 
threads "action". Not alwyas a problem, but...

What is  thread suposed to do to "kill time"? e.i. let other things run 
with out using up much CPU but keep poling the thread.

while(NothingToDo())
	thisThread.MarkTime();


More information about the Digitalmars-d-learn mailing list