我正在尝试为并行计算实现线程工作者。我遇到的问题是 的quit()
插槽thread
没有被触发,因此应用程序在while(thread->isRunning())
. 是否可以停止thread
在worker
它们之间使用信号槽连接?这是我的代码:
主.cpp:
#include <QCoreApplication>
#include "workermanager.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
WorkerManager workerManager;
workerManager.process();
return a.exec();
}
工人.h:
#include <QObject>
#include <QDebug>
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0) :
QObject(parent){}
signals:
void processingFinished();
public slots:
void process()
{
qDebug() << "processing";
emit this->processingFinished();
}
};
工人经理.h:
#include "worker.h"
#include <QThread>
class WorkerManager : public QObject
{
Q_OBJECT
public:
explicit WorkerManager(QObject *parent = 0) :
QObject(parent){}
void process()
{
QThread* thread = new QThread;
Worker* worker = new Worker;
connect(thread,SIGNAL(started()),worker,SLOT(process()));
connect(worker,SIGNAL(processingFinished()),thread,SLOT(quit()));
worker->moveToThread(thread);
thread->start();
qDebug() << "thread started";
while(thread->isRunning())
{
}
qDebug() << "thread finished";
//further operations - e.g. data collection from workers etc.
}
};