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?
‘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.