On 2011-06-03 14:37, Andrej Mitrovic wrote: > On 6/3/11, Jonathan M Davis <jmdavisp...@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)); > }
Yeah. That looks fine, though currTime isn't a property (it takes an optional TimeZone object), so technically it should have parens. That's obviously not enforced at the moment though. In any case, it's essentially fine, but has 2 potential issues, depending on how accurate you want the timing to be or how responsive you want the loop to be in exiting. First off, you pay no attention whatsoever to how close the current time is to the final time such that there could be a few microseconds of difference between them and you'd still sleep for a whole second before exiting. If you want it to be more accurate, then it should be something more like while(engineActive) { auto curr = Clock.currTime(); if(curr > finalTime) break; Thread.sleep(dur!"seconds(min(1, (finalTime - currTime).total!"seconds"()))); } Incidentally, this use case shows that I should probably add overloads for some of the basic math functions for Duration... In any case, such an implementation would make it so that it doesn't sleep for longer than it needs to. The other potential issue is responsiveness. If you want the loop to exit quickly after engineActive has been set to true, then you should probably be setting sleep to something more like 100ms (though if you set the value too low, then the loop wakes up more often than might be desirable, so it's a bit of a balancing act). Regardless, the only potential issues lie with how quickly you want the loop to exit after the exit condition has been reached. - Jonathan M Davis