Is this a good way of setting up a timer?

Steven Schveighoffer schveiguy at yahoo.com
Mon Jun 6 07:28:29 PDT 2011


On Fri, 03 Jun 2011 17:37:40 -0400, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> On 6/3/11, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
>>
>> Generally, you'd just put it to sleep for the period of time that you  
>> want
>> to
>> wait for. The only reason that I see to keep waking it up is if it  
>> could be
>> interrupted and effectively told to wake up - in which case you would be
>> sleeping and waking up over and over again, checking to see if enough  
>> time
>> had
>> passed or if you had been signaled to stop waiting.
>
> Yeah, I should have made a better example. Basically I have a loop
> that ends either after a specific time period, or it could end by
> receiving a signal. I just use a shared book for that, this would be
> it:
>
>     while (engineActive)  // shared bool
>     {
>         if (Clock.currTime > finalTime)
>             break;
>
>         Thread.sleep(dur!("seconds")(1));
>     }
>

I'm going to put on my old-school concurrency hat here :)

How I would write this is with a mutex and a condition.  Then instead of  
sleeping, I'd wait for the conditional.  I.e.:

while(engineActive) // shared bool
{
    auto curtime = Clock.currTime;
    if(curtime > finalTime)
       break;
    synchronized(mutex) cond.wait(finalTime - curTime);
}

Then, you have a function that sets the bool and signals the condition:

void endProgram()
{
    synchronized(mutex)
    {
       if(engineActive)
       {
           engineActive = false;
           cond.notifyAll();
       }
    }
}

Taking my hat off, I think the better way to do this is with  
std.concurrency.  But I have zero experience with it.  I'd guess there are  
ways to wait on your message queue, and some way to broadcast a message to  
all threads.

In any case, sleeping for a set period of time, and then checking a  
boolean works, but is both inefficient and less responsive than waiting  
for the exact condition you are looking for.

Trouble is, in some cases, a thread is waiting for *multiple* conditions,  
like input from a stream or exiting the program.  On some oses, it's very  
difficult to wait for both of those.  There are ways to solve this with  
helper threads, but this can also be wasteful.  Without further details on  
what your thread is doing, I can't say whether this would be a problem for  
you.

What I've done in the past is wait for the condition that needs to be more  
responsive (i.e. handling I/O) and use a timeout that allows a reasonable  
response to the other condition.

-Steve


More information about the Digitalmars-d-learn mailing list