What about a Thread::sleepOrExit(const int sleepTimeMillisecond) method, that does sleep for the given time, while still checking threadShouldExit regularly and exiting then ?

The code is very simple:

    /** Sleep this thread for the given duration in millisecond.
         Contrary to Thread::sleep, if the thread is signaled to exit, this method exit immediately instead of after the duration time elapsed. */
    bool sleepOrExit(const unsigned int durationMs) const
         double endTime = Time::getMillisecondCounter() + durationMs;
         while (!threadShouldExit() && Time::getMillisecondCounter() < endTime) sleep(roundDoubleToInt(jlimit(0, 30.0, endTime - Time::getMillisecondCounter())));


I prefer to use wait() for that - it’ll get interrupted when the thread is told to stop, so it basically does exactly what you’re asking for there.


Yes you’re right.

Here’s another version that does check an external event at the same time.

    /** Wait for a signaled event or end of thread */
    bool waitForEvent(WaitableEvent & event, const int timeoutMs)
        double endTime = Time::getMillisecondCounter() + timeoutMs;
        bool ret = false;
        while (!threadShouldExit() && !(ret = event.wait(roundDoubleToInt(jlimit(0.0, 20.0, endTime - Time::getMillisecondCounter())))) && Time::getMillisecondCounter() < endTime);
        return ret;