With Qthread in mind I tried the following but it seems everything is still running in the same thread.
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
widget.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
Running I get the output:
int main(int, char **) 0x107567e00
Func::Func() 0x107567e00
Widget::Widget(Core &) 0x107567e00
void Func::compute() 0x107567e00
Above output was from macOS but in Windows I got similar result.
So what am I doing wrong?
CodePudding user response:
You cannot call the slot compute()
directly, it will call it in the same thread as runs the code which called it (as you can see in the output).
You need to run the slot via signals/slots mechanism (or with invokeMethod()
, but let's ignore this one).
Typically this is done by connecting thread's started()
signal to the slot and then calling QThread::start()
from the main thread. It will result in slot being called in the secondary thread just after the thread gets started.