考慮到Qthread,我嘗試了以下操作,但似乎所有內容仍在同一執行緒中運行。
主程式
#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();
}
函式檔案
#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
核心檔案
#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 中我得到了類似的結果。
那么我做錯了什么?
uj5u.com熱心網友回復:
您不能compute()直接呼叫插槽,它會在運行呼叫它的代碼的同一執行緒中呼叫它(如您在輸出中所見)。
您需要通過信號/插槽機制(或使用invokeMethod(),但讓我們忽略這一點)來運行插槽。
通常這是通過將執行緒的started()信號連接到插槽然后QThread::start()從主執行緒呼叫來完成的。這將導致在執行緒啟動后立即在輔助執行緒中呼叫插槽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327431.html
