main()つまりメインスレッドにQThreadを作成しました。 ワーカークラスを新しいスレッドに移動しました。スレッドは、ワーカークラスの 'StartThread'メソッドを実行します。Stop Qt Thread:exit()またはquit()を呼び出してもスレッドの実行が停止しない
ワーカースレッド: 'StartThread' 完了し、スレッドが正常に終了する前に
//header file
class Worker : public QObject
{
Q_OBJECT
public:
Worker(QThread* thread);
public slots:
void StartThread();
void EndThread();
private:
QThread* m_pCurrentThread;
};
// source file
#include "QDebug"
#include "QThread"
#include "worker.h"
Worker::Worker(QThread* thread)
{
m_pCurrentThread = thread;
}
void Worker::StartThread()
{
qDebug() << " StartThread";
while(true)
{
QThread::msleep(1000);
qDebug() << " thread running";
static int count = 0;
count++;
if(count == 10)
{
break;
}
if(m_pCurrentThread->isInterruptionRequested())
{
qDebug() << " is interrupt requested";
// Option 3:
m_pCurrentThread->exit();
}
}
qDebug() << "StartThread finished";
}
void Worker::EndThread()
{
qDebug() << "thread finished";
}
MAIN.CPP
#include <QCoreApplication>
#include "worker.h"
#include "QThread"
#include "QObject"
#include "QDebug"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThread* thread = new QThread();
Worker* workerObj = new Worker(thread);
QObject::connect(thread,
SIGNAL(started()),
workerObj,
SLOT(StartThread()));
QObject::connect(thread,
SIGNAL(finished()),
workerObj,
SLOT(EndThread()));
workerObj->moveToThread(thread);
thread->start();
thread->requestInterruption();
QThread::msleep(2000);
qDebug() << "terminate thread";
if(thread->isRunning())
{
// Option 1,2 exit()/quit() used but got same output
thread->exit();
qDebug() << "wait on thread";
thread->wait();
}
qDebug() << " exiting main";
return a.exec();
}
は、今私はメインスレッドからスレッドを停止します。 が使用される、
- スレッド>の出口() メインスレッドで(スレッド>待つ())を待っていました。
thread-> quit() メインスレッドの待機(thread-> wait())。
の出口()の 'StartThread'
予想:は スレッドの実行が()/終了終了するとすぐに停止する必要があります()メインスレッドから呼び出されます。
は実際: スレッドが稼働し続け、すべての3つのインスタンスでは、「StartThread」メソッドを完了し、正常に終了します。 exit()/ quit()が呼び出されていない場合と同様に良好です。 出力:
StartThread
thread running
is interrupt requested
terminate thread
wait on thread
thread running
is interrupt requested
thread running
is interrupt requested
thread running
is interrupt requested
thread running
is interrupt requested
thread running
is interrupt requested
thread running
is interrupt requested
thread running
is interrupt requested
thread running
is interrupt requested
thread running
StartThread finished
thread finished
exiting main
はそれがメインスレッドで必要とされるときのようにスレッドを配置/停止することは可能ですか?