与QThreadPool的跨线程插槽信号关系

时间:2018-11-28 17:43:58

标签: c++ multithreading qt

我需要在QThreadPool中运行任务,并在需要时从工作线程发出信号。我发现这样的实现:

task.h

class Task : public QObject
{
    Q_OBJECT
public:
    explicit Task(QObject *parent = nullptr);
    void run(QThreadPool *pool);

signals:
    void finished(QString result);
}; 

task.cpp

#include "task.h"

Task::Task(QObject *parent) : QObject(parent)
{

}

void Task::run(QThreadPool *pool)
{
    QtConcurrent::run(pool, [this](){
        qDebug() << "Task in thread " << QThread::currentThreadId();
        emit finished(QString("value"));
    });
}

main.cpp

#include <QApplication>
#include <QLabel>

#include "task.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLabel label("waitinig...");
    label.show();
    Task task;
    QObject::connect(&task, SIGNAL(finished(QString)), &label, SLOT(setText(QString)));

    QThreadPool *pool = new QThreadPool;
    task.run(pool);
    qDebug() << "main thread id: " << QThread::currentThreadId();

    return a.exec();
}

此代码似乎正常工作,但我不确定这是正确的方法 要做到这一点。

0 个答案:

没有答案