Reputation: 506995
I'm in a worker thread and want to sleep for a specified period of time (usually a few hundreds milliseconds), but the sleep should be interruptible. Here is what I have come up with
void DummyScope::sleepForSamples() {
if(m_sampleSleep < 100) {
MySleeper::sleep(m_sampleSleep);
return;
}
// sleep in periods of 100 ms, to be responsible for shutdown requests
qint64 t = QDateTime::currentMSecsSinceEpoch();
qint64 end = t + m_sampleSleep;
while(t + 100 <= end) {
MySleeper::sleep(100);
t = QDateTime::currentMSecsSinceEpoch();
// TODO: check here whether we are interrupted
}
if(end > t) {
MySleeper::sleep(end - t);
}
}
However that looks a bit convoluted and I wonder whether there's a better way to do this. Is using a QWaitCondition
with a timeout-wait a better solution?
Upvotes: 2
Views: 1116
Reputation: 29886
You can wait directly on the mutex with QMutex::tryLock(int timeout)
, if you lock and unlock it from another thread.
Upvotes: 0
Reputation: 14392
Definitely wait on a condition variable and let the accompanying condition tell you why you were interrupted.
If you don't have to use QT-threads, c++11 and boost let you add a predicate to wait_for/timed_wait, so spurious wakeups don't mess with your timeout.
Of course, it is even more convienent if you can go 1 step further and don't bother with a timeout (if the condition variable can handle all cases).
Upvotes: 0
Reputation: 24857
'Is using a QWaitCondition with a timeout-wait a better solution?'
Yes!
The sleep() loop, apart from needlessly running every 100ms, has an average 'interrupt' latency of 50ms.
Upvotes: 2