对于moveToThread()函数,我做了下面的验证。
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QThread>
#include <mythread.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void go1();
private:
Ui::MainWindow *ui;
signals:
void sig1();
public:
MyThread mt;
QThread th;
};
#endif // MAINWINDOW_H
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QDebug>
#include <QThread>
class MyThread : public QObject
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
void fun1();
signals:
public slots:
void recvSig1();
void recvSig2();
};
#endif // MYTHREAD_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mt.moveToThread(&th);
th.start();
go1();
connect(this,SIGNAL(sig1()),&mt,SLOT(recvSig1()));
connect(this,SIGNAL(sig1()),&mt,SLOT(recvSig2()));
emit sig1();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::go1()
{
qDebug()<<"go1 thread is"<<QThread::currentThreadId();
mt.recvSig1();
}
mythread.cpp
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QObject(parent)
{
}
void MyThread::fun1()
{
qDebug()<<"fun1 thread is "<<QThread::currentThreadId();
}
void MyThread::recvSig1()
{
fun1();
qDebug()<<"recvSig1 thread is "<<QThread::currentThreadId();
}
void MyThread::recvSig2()
{
qDebug()<<"recvSig2 thread is "<<QThread::currentThreadId();
}
输出为:
go1 thread is 0x30f0
fun1 thread is 0x30f0
recvSig1 thread is 0x30f0
fun1 thread is 0x11a0
recvSig1 thread is 0x11a0
recvSig2 thread is 0x11a0
有以下几点结论:
1.只有通过信号槽的机制触发的函数才会在子线程中运行,直接调用的函数会在对应的主线程运行。
2.线程内直接调用的函数在同一线程中执行,这也是上面后半句的支撑。
参考链接: https://blog.csdn.net/lin_duo/article/details/100120932