スリープ中に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();です。スレッドがスリープしている5秒待機する必要があります。彼が続けることができるように、私はただ「睡眠からの目覚め」のようなものを呼ぶことができますか?
それとも、これを行うためのより良い方法はありますか?
/ありがとう
アップデート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は、彼を開始および停止するのと同じトレッドでない場合に破損するため、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();
}