您的当前位置:首页正文

Qt多线程问题

来源:要发发知识网

main.cpp

#include <QCoreApplication>
#include <QThread>
#include <QDebug>

#include "hello.h"

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

    qDebug() << "main thread" << QThread::currentThreadId();

    QThread thread;
    thread.start();

    Hello test;
    test.moveToThread(&thread);

    // 子线程调用
    emit test.callTest(3);

    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 callTest(int num);

public slots:
    void testThread(int num);

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)
{
    connect(m_timer, &QTimer::timeout, [=](){
        // 主线程调用
        testThread(1);

        // 子线程调用
        QMetaObject::invokeMethod(this, "testThread", Qt::QueuedConnection, Q_ARG(int, 2));
    });
    m_timer->start(1000);

    connect(this, &Hello::callTest, this, &Hello::testThread);
}

void Hello::testThread(int num)
{
    qDebug() << "num" << num << "testThread" << QThread::currentThreadId();
}

测试结果

2019-02-17_135030.png

结论:

将对象放到单独线程中后

  1. 直接调用对象的方法,方法在主线程(红色框)中运行
  2. 通过信号调用或者invokeMoethod调用,方法在子线程(绿色框)中运行