我在一个工作线程中,想睡一段指定的时间(通常是几百毫秒),但睡眠应该是可以中断的。以下是我想出了Qt中的可中断睡眠?
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);
}
}
然而,看起来有点令人费解,我不知道是否有更好的方法来做到这一点。正在使用带有超时的QWaitCondition
-等待更好的解决方案?
你能给一个理由/一些背景吗?像等待条件和互斥体听起来像重POSIX的东西。相反,在我的循环中只有基本的睡眠。 – 2012-04-05 12:08:47
只需'如果QWaitCondition :: wait(timeout)'就不需要任何互斥体。 – 2012-04-05 12:16:25
@ JohannesSchaub-litb我认为这是因为有了计时器,你的进程永远不会醒来,相反它是OS调度程序,可以检测你的进程何时需要中断。此外,这有一个更好的延迟,随着你的循环,在你处理一个事件之前,你的超时/ 2的平均延迟将会被调整。 – sashoalm 2012-04-05 12:17:46