Qt线程QThread

对于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值