[英]Error connecting Worker Thread signal with MainWindow slot (Qt5)
[英]Is it possible for a worker to stop it's own thread with signal/slot connection in Qt?
我正在尝试为并行计算实现线程工作器。 我遇到的问题是thread
的quit()
插槽未触发,因此应用程序在while(thread->isRunning())
处等待。 是否可以使用它们之间的信号插槽连接来停止worker
thread
? 这是我的代码:
main.cpp:
#include <QCoreApplication>
#include "workermanager.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
WorkerManager workerManager;
workerManager.process();
return a.exec();
}
worker.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();
}
};
workermanager.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.
}
};
该while循环会阻塞您的线程并阻止其处理任何信号,如果您确实要等待线程完成,则需要启动事件循环。
尝试以下方法:
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);
QEventLoop loop;
connect(thread, &QThread::finished, &loop, &QEventLoop::quit);
qDebug() << "thread started";
thread->start();
loop.exec();
qDebug() << "thread finished";
//further operations - e.g. data collection from workers etc.
}
但是我不得不承认我并没有真正理解这段代码的意义。 如果您需要等待任务完成才能继续工作,则最好直接运行它。 在此期间,至少您的程序将能够处理其他内容(如果有的话)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.