Implementing a timer using threads
BCS
BCS at pathlink.com
Mon Jan 29 10:55:37 PST 2007
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();
}
}
}
More information about the Digitalmars-d-learn
mailing list