worker是否可以在Qt中使用信号/插槽连接停止自己的线程?



我正在尝试实现线程工作线程以进行并行计算。我遇到的问题是没有触发threadquit()槽,因此应用程序在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.
    }
};
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.
}

但我不得不承认,我并没有真正看到这段代码的意义。如果您需要等待任务完成以继续执行操作,则不妨直接运行它。至少你的程序将能够同时处理其他事情(如果有的话)。

最新更新