Qt多线程实现方法

本文详细介绍了Qt库中实现多线程的四种方法:1) 继承QThread并重写run方法;2) 使用moveToThread方法;3) 利用QtConcurrent::run创建临时线程;4) 通过信号和槽处理线程间的通信。文中还解析了信号和槽在线程间连接时的不同执行情况。
摘要由CSDN通过智能技术生成

Qt提供了三种实现多线程的方式:
1)继承QThread,重写run方法
代码如下:

MyThread::MyThread(QObject *parent)
    :QThread(parent){
}
void MyThread::run()
{
    QTimer *timer = new QTimer();
    connect(timer,&QTimer::timeout,this,[](){
        qDebug() << "TMyThreadID:::" << QThread::currentThreadId();
    });
    timer->start(1000);
    this->exec();//注意:必须调用exec才会进入事件循环
}

2)moveToThread(官方推荐)
代码如下:

class Test : public QObject
{
    Q_OBJECT
public:
    Test(QObject *parent = nullptr):QObject(parent){}
    ~Test(){}
    void test(){qDebug() << "testThreadID" << QThread::currentThreadId();}
};
 void  MyThread()
 {
  	QThread *thread = new QThread(this);
    Test *testObj = new Test();
    testObj->moveToThread(thread);
    QPushButton *pBtn = new QPushButton(this);
    connect(pBtn,&QPushButton::clicked,testObj,&Test::test);
    qDebug() << "mainThreadID" << QThread::currentThreadId();
    thread->start();
 }

3)QtConcurrent::run方法(临时线程)

QtConcurrent::run([=]()
{
	qDebug() << "QtConcurrentID" << QThread::currentThreadId();
});

4)信号和槽函数执行线程说明
a.如果信号和槽在同一个线程,槽在发送信号所在线程执行
b.如果信号和槽在不同线程,且connect第五个参数为Qt::DirectConnection,槽在发送信号所在线程中执行
c.如果信号和槽在不同线程,且connect第五个参数为Qt::QueuedConnection,槽在接受所在线程中执行

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值