0

我正在尝试为并行计算实现线程工作者。我遇到的问题是 的quit()插槽thread没有被触发,因此应用程序在while(thread->isRunning()). 是否可以停止threadworker它们之间使用信号槽连接?这是我的代码:

主.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.

    }
};
4

1 回答 1

0

那个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.

}

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

于 2015-01-21T06:04:31.457 回答