main.cpp
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include "hello.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "main thread id" << QThread::currentThreadId();
QThread thread;
thread.start();
Hello test;
test.moveToThread(&thread);
test.testThread("直接調(diào)用");
// 子線程調(diào)用
emit test.callTheadFun("通過emit調(diào)用");
// 子線程調(diào)用
QMetaObject::invokeMethod(&test, "testThread", Qt::QueuedConnection, Q_ARG(QString, "通過invokeMethod調(diào)用"));
return a.exec();
}
hello.h
#ifndef HELLO_H
#define HELLO_H
#include <QObject>
#include <QTimer>
class Hello : public QObject
{
Q_OBJECT
public:
explicit Hello(QObject *parent = nullptr);
signals:
void callTheadFun(QString msg);
public slots:
void testThread(const QString &msg);
void testConnect();
private:
QTimer *m_timer;
};
#endif // HELLO_H
hello.cpp
#include <QDebug>
#include <QThread>
#include "hello.h"
Hello::Hello(QObject *parent)
: QObject(parent)
, m_timer(new QTimer)
{
// 定時(shí)器中,直接調(diào)用lambda函數(shù)時(shí), 主線程調(diào)用
connect(m_timer, &QTimer::timeout, [=](){
qDebug() << "定時(shí)器中混槐,直接調(diào)用lambda函數(shù)時(shí), thread id" << QThread::currentThreadId();
});
// 定時(shí)器中测僵,將lambda作為成員函數(shù)調(diào)用時(shí), 子線程調(diào)用
connect(m_timer, &QTimer::timeout, this, [=](){
qDebug() << "定時(shí)器中希太,將lambda作為成員函數(shù)調(diào)用時(shí), thread id" << QThread::currentThreadId();
});
// 定時(shí)器中戈泼,調(diào)用成員函數(shù),子線程調(diào)用
connect(m_timer, &QTimer::timeout, this, &Hello::testConnect);
m_timer->setSingleShot(true);
m_timer->start(1000);
// auto connect, 子線程調(diào)用
connect(this, &Hello::callTheadFun, this, &Hello::testThread);
}
void Hello::testThread(const QString &msg)
{
qDebug() << "in testThread" << msg << "thread id" << QThread::currentThreadId();
}
void Hello::testConnect()
{
qDebug() << "定時(shí)器中平痰,調(diào)用成員函數(shù), thread id" << QThread::currentThreadId();
}
測(cè)試結(jié)果
結(jié)論:
將對(duì)象放到單獨(dú)線程中后
- 直接調(diào)用對(duì)象的方法款违,方法在主線程中運(yùn)行
- 通過信號(hào)(emit)調(diào)用或者invokeMoethod調(diào)用,函數(shù)在子線程中運(yùn)行
- 定時(shí)器中团南,直接調(diào)用lambda函數(shù)時(shí), 函數(shù)在主線程調(diào)用
- 定時(shí)器中,將lambda作為成員函數(shù)調(diào)用時(shí)或者直接調(diào)用成員函數(shù)時(shí), 函數(shù)在子線程運(yùn)行