如何在睡眠时唤醒QThread?
我有一个在后台运行的线程,现在然后醒来并做一些小事情,但是如果我想以受控方式停止该线程,我必须等待他自己醒来以便让他退出而且由于他睡了很长时间,这可能会非常烦人.
让我们从在这个例子中休眠5秒然后只打印一个点的线程开始.
#include <QDebug> #include "TestThread.h" void TestThread::run() { running = true; while(running == true) { qDebug() << "."; QThread::sleep(5); } qDebug() << "Exit"; } void TestThread::stop() { running = false; }
然后我们有主要开始线程然后杀死他.
#include <QDebug> #include "TestThread.h" int main(int argc,char *argv[]) { qDebug() << "Start test:"; TestThread *tt = new TestThread(); tt->start(); sleep(2); tt->stop(); tt->wait(); delete tt; }
问题是tt-> wait();必须等待线程正在休眠的5s.
我可以称之为“从睡眠中醒来”,这样他就可以继续.
或者有更好的方法吗?
/谢谢
更新我使用QMutex和tryLock:
#include <QDebug> #include "TestThread.h" QMutex sleepMutex; void TestThread::run() { qDebug() << "Begin"; //1. Start to lock sleepMutex.lock(); //2. Then since it is locked,we can't lock it again // so we timeout now and then. while( !sleepMutex.tryLock(5000) ) { qDebug() << "."; } //4. And then we cleanup and unlock the lock from tryLock. sleepMutex.unlock(); qDebug() << "Exit"; } void TestThread::stop() { //3. Then we unlock and allow the tryLock // to lock it and doing so return true to the while // so it stops. sleepMutex.unlock(); }
但是使用QWaitCondition会更好吗?还是一样吗?
更新:如果QMutex与启动和阻止他的步伐不同,QMutex会中断,
所以这是QWaitCondition的尝试.
#include <QDebug> #include <QWaitCondition> #include "TestThread.h" QMutex sleepMutex; void TestThread::run() { qDebug() << "Begin"; running = true; sleepMutex.lock(); while( !waitcondition.wait(&sleepMutex,5000) && running == true ) { qDebug() << "."; } qDebug() << "Exit"; } void TestThread::stop() { running = false; waitcondition.wakeAll(); }@H_403_32@