【发布时间】:2016-06-24 21:10:16
【问题描述】:
在 main() 中创建了一个 QThread,即主线程。 将工人类移至新线程。线程执行worker类的'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();
}
现在,在“StartThread”完成并优雅退出线程之前,我想从主线程中停止线程。 用过,
- 线程->退出() 并在主线程中等待 (thread->wait())。
线程->退出() 并在主线程中等待 (thread->wait())。
“StartThread”中的exit()
预期: 一旦从主线程调用 exit()/quit(),线程执行应该停止。
实际: 在所有三个实例中,线程继续运行,完成“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
是否可以在主线程需要时停止/处置线程?
【问题讨论】: