Qt实现多线程的两种方式

1、继承QThread类,重写run函数。此实现方法只有run函数内的代码是运行在子线程内。

代码示例:

#ifndef QDEMOTHREAD_H
#define QDEMOTHREAD_H

#include <QThread>
#include <QDebug>

class QDemoThread : public QThread
{
   
    Q_OBJECT

public:
    QDemoThread(QObject* parent = nullptr);
    ~QDemoThread();

protected:
    void run() override;

public:
    void stop();

private:
    bool flag;
};

#endif // QDEMOTHREAD_H
#include "qdemothread.h"

QDemoThread::QDemoThread(QObject* parent) : QThread(parent)
{
   
    

}

QDemoThread::~QDemoThread()
{
   
    

}

void QDemoThread::run()
{
   
    
    flag = true;
    while(flag)
    {
   
    
        qDebug() << "thread id:" << QThread::currentThreadId();
        sleep(1);
    }
}

void QDemoThread::stop()
{
   
    
    flag = false;
    if(isRunning())
    {
   
    
        exit();  // 结束线程
        wait();  // 等待退出
    }
}

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
   
    
    ui->setupUi(this);

    demoThread = new QDemoThread(this);

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

Widget::~Widget()
{
   
    
    demoThread->stop();  // 退出线程
    delete ui;
}

void Widget::on_pushButton_clicked()
{
   
    
    if(!demoThread->isRunning())
    {
   
    
        demoThread->start();  // 启动线程
    }
}

2、创建一个QThread和QWorker(继承自QObject)类对象,使用moveToThread函数移动到thread中运行,通过thread类start信号和worker槽函数绑定

示例代码:
QWorker类:

#ifndef QWORKER_H
#define QWORKER_H

#include <QObject>
#include <QThread>
#include <QDebug>

class QWorker : public QObject
{
   
     
    Q_OBJECT
public:
    explicit QWorker(QObject *parent = nullptr);

signals:

public slots:
    void doWork();
};

#endif // QWORKER_H

#include "qworker.h"

QWorker::QWorker(QObject *parent) : QObject(parent)
{
   
}

void QWorker::doWork()
{
   
    qDebug() << "thread id:" << QThread::currentThreadId();
}

启动线程:

QWorker* worker = new QWorker();
QThread* thread = new QThread();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值