微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/118577.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐