【问题标题】:How to run it on another Qt thread?如何在另一个 Qt 线程上运行它?
【发布时间】:2021-12-04 06:30:38
【问题描述】:

考虑到Qthread,我尝试了以下操作,但似乎一切仍在同一个线程中运行。

main.cpp

#include "widget.h"

#include <QApplication>

#include "core.h"

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

    qDebug() << Q_FUNC_INFO << QThread::currentThreadId();

    Core core;

    Widget w(core);
    w.show();

    return a.exec();
}

func.h

#ifndef FUNC_H
#define FUNC_H

#include <QDebug>
#include <QThread>

class Func : public QObject
{
    Q_OBJECT
public:
    explicit Func()
    {
        qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
    }

    void compute()
    {
        qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
    }
};

#endif // FUNC_H

core.h

#ifndef CORE_H
#define CORE_H

#include <QObject>

#include "func.h"

class Core : public QObject
{
    Q_OBJECT

    QThread thread;
    Func* func = nullptr;

public:
    explicit Core(QObject *parent = nullptr)
    {
        func = new Func();
        func->moveToThread(&thread);
        connect(&thread, &QThread::finished, func, &QObject::deleteLater);
        thread.start();
    }

    ~Core() {
        thread.quit();
        thread.wait();
    }

public slots:
    void compute(){func->compute();}

signals:

};

#endif // CORE_H

小部件.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

#include "core.h"

class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(Core& core)
    {
        qDebug() << Q_FUNC_INFO << QThread::currentThreadId();

        core.compute(); // This should run on a different thread ?
    }

};

#endif // WIDGET_H

运行我得到输出:

int main(int, char **) 0x107567e00
Func::Func() 0x107567e00
Widget::Widget(Core &) 0x107567e00
void Func::compute() 0x107567e00

以上输出来自 macOS,但在 Windows 中我得到了类似的结果。

那我做错了什么?

【问题讨论】:

    标签: c++ multithreading qt qt5 qthread


    【解决方案1】:

    您不能直接调用插槽compute(),它将在运行调用它的代码的同一线程中调用它(如您在输出中看到的那样)。

    您需要通过信号/插槽机制(或使用invokeMethod(),但我们忽略这个)运行插槽。

    通常这是通过将线程的started() 信号连接到插槽然后从主线程调用QThread::start() 来完成的。这将导致在线程启动后立即在辅助线程中调用槽。

    【讨论】:

    • 知道了!当对该对象的方法的调用不是间接调用时,发出警告会很有趣。在这方面有什么建议吗?理想情况下,我想保证对该对象上的方法的调用(仅)在另一个线程上运行。
    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多