c – 唤醒处于睡眠状态的QThread?

如何在睡眠时唤醒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();
}

解决方法

您可以使用 QWaitCondition而不是简单的睡眠.如果给你更多的控制权.

示例用法Wait Conditions Example

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...