Qt线程简单使用三:QRunnable~线程池

发布时间 2023-05-30 00:18:31作者: 十一的杂文录

 

需求:
  点击QPushButton按钮,QLabel中的数字,不断累加,一直到999。
 
做法:
  创建任务类,点击QPushButton后,将任务类放入线程池中运行,通过任务类while循环,不断发送累加的数字回主线程,修改QLabel中的数字
 
其他:
  线程池的好处是可以最大程度的利用线程,减少资源的浪费。
  本示例看不出效果,要是有兴趣,可以多写几个任务,都添加到线程池中,每个任务都打印下线程id,这样就可以看出效果了。
 
主要代码:
// MyThread.h

#pragma once

#include <QObject>
#include <QThread>
#include <QRunnable>

class MyRunnable  : public QObject, public QRunnable
{
    Q_OBJECT

public:
    MyRunnable(QObject *parent=nullptr);
    ~MyRunnable();
    
    void run();

signals:
    void sendNum(int num);
};

 

// MyThread.cpp

#include "MyThread.h"

MyRunnable::MyRunnable(QObject *parent)
    : QObject(parent), QRunnable()
{
    // 设置工作完成后自动析构
    setAutoDelete(true);
}

MyRunnable::~MyRunnable()
{}

void MyRunnable::run()
{
    int num = 0;
    while (num < 1000)
    {
        emit sendNum(num);
        num++;
        QThread::msleep(5);
    }
}

 

// QtWidgetsApplication1.cpp

#include "MyThread.h"
#include <QThreadPool>

MyWidget::MyWidget(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);

    // 1.创建任务类对象
    MyRunnable* work = new MyRunnable;

    // 开始工作
    connect(work, &MyRunnable::sendNum, this, [=](int num) {ui.label->setText(QString::number(num)); });
    connect(ui.pushButton, &QPushButton::clicked, this, [=]() 
        {
            // 2.将任务类对象放到线程池中
            QThreadPool::globalInstance()->start(work);
        });    
}

 

 
 
 
 
 
参考文档:爱编程的大丙:https://subingwen.cn/qt/thread/