QThreadPool线程池与QRunnable-QT5.6.2/麒麟/x86

  • Post author:
  • Post category:其他




1. 介绍

线程的创建及销毁需要与系统交互,会产生很大的开销。若需要频繁的创建线程建议使用线程池,有线程池维护一定数量的线程,当需要进行多线程运算时将运算函数传递给线程池即可。线程池会根据可用线程进行任务安排。



2. QThreadPool

相关帮助文档:QThreadPool

此类为Qt提供的线程池函数,使用此类只需要配置线程池的最大线程数量、线程长时间不使用的过期时间等参数,不需要进行QThread相关的操作。

此类有两种使用方式:全局线程池和局部线程池。下面首先介绍两种类型后续介绍类提供的方法



2.1. 基本操作函数

int activeThreadCount() const //当前的活动线程数量

void clear()//清除所有当前排队但未开始运行的任务

int expiryTimeout() const//线程长时间未使用将会自动退出节约资源,此函数返回等待时间

int maxThreadCount() const//线程池可维护的最大线程数量

void releaseThread()//释放被保留的线程

void reserveThread()//保留线程,此线程将不会占用最大线程数量,从而可能会引起当前活动线程数量大于最大线程数量的情况

void setExpiryTimeout(int expiryTimeout)//设置线程回收的等待时间

void setMaxThreadCount(int maxThreadCount)//设置最大线程数量

void setStackSize(uint stackSize)//此属性包含线程池工作线程的堆栈大小。

uint stackSize() const//堆大小

void start(QRunnable *runnable, int priority = 0)//加入一个运算到队列,注意start不一定立刻启动,只是插入到队列,排到了才会开始运行。需要传入QRunnable ,后续介绍

bool tryStart(QRunnable *runnable)//尝试启动一个

bool tryTake(QRunnable *runnable)//删除队列中的一个QRunnable,若当前QRunnable 未启动则返回成功,正在运行则返回失败

bool waitForDone(int?

msecs

?=?-1)//等待所有线程运行结束并退出,参数为等待时间-1表示一直等待到最后一个线程退出



2.2. 全局线程池

QThreadPool提供了一个静态函数,globalInstance(),使用此方法可获取一个当前进程的全局线程池,可在多个类中共同使用一个线程池。



2.3. 局部线程池

和常规类的使用相同,可以通过? QThreadPool pool;的方式建立一个局部线程池,并由当前类维护,可保证此线程池仅供当前类应用



3. QRunnable

线程池每一个需要运行的任务均需要作为QRunnable的子类,并重写其run函数,帮助文档:http://doc.qt.io/qt-5/qrunnable.html

QRunnable只有run、autodelete、setautodelete这三个关键函数。

run内重写需要运算的内容。

autodelete用来标识是否在运行结束后自动由线程池释放空间,具体说明见上述“QThreadPool-基本操作函数-start tryStart tryTake”



4.实例



qmyrunnable.h

#ifndef QMYRUNNABLE_H
#define QMYRUNNABLE_H

#include <QObject>
#include "widget.h"
class Widget;
typedef QString (Widget::*func)(int);
/**
 * @brief The QMyRunnable class:
 * QRunnable没有父类,也不能继承QObject,因此如果多重继承QObjec的情况下,会提示信号没有定义
 * 在run中执行传入指针的成员函数,相当于在线程里执行,不是主线程
 * Widget::Widget thread  id is         0x7ffff7fe1840
 * main  id is                          0x7ffff7fe1840
 * Widget::Update_Result thread  id is  0x7fffd14a6700
 */
class QMyRunnable : public QRunnable
{
public:
    QMyRunnable(func func, int, QObject* obj);
protected:
    void run();
signals:
    void sigUpdate_Result(QString str);
private:
    QObject* _obj;
    int _param;
    QString (Widget::*_func)(int);//函数指针
};

#endif // QMYRUNNABLE_H



qmyrunnable.cpp

#include "qmyrunnable.h"
#include "widget.h"
QMyRunnable::QMyRunnable(func func,int param,QObject* obj)
    : _func(func)
    ,_param(param)
    ,_obj(obj)
{    
}
void QMyRunnable::run()
{
    Widget *pf = (Widget*)_obj;
    QString str = (pf->*_func)(_param);
    pf->Update_Result(str);
    return;
}



widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QThreadPool>
#include "qmyrunnable.h"
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

public slots:
    void on_emit_Btn_clicked();
    void Update_Result(QString str);
public:
    QString absolute(int a);
private:
    Ui::Widget *ui;
    QThreadPool MyThreadPool;
};

#endif // WIDGET_H



widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    MyThreadPool.setMaxThreadCount(2);
    MyThreadPool.setParent(this);

    qWarning()<<"Widget::Widget thread  id is "<<QThread::currentThreadId();
}

Widget::~Widget()
{
    MyThreadPool.waitForDone();
    delete ui;
}

void Widget::on_emit_Btn_clicked()
{
    MyThreadPool.start(new QMyRunnable(&Widget::absolute,1,this));//将函数指针和参数传递进去(函数名即可以理解为函数指针)
}

QString Widget::absolute(int a)
{
    return QString("abs(%1)=%2").arg(a).arg(abs(a));
}

void Widget::Update_Result(QString str)
{
    qWarning()<<"Widget::Update_Result thread  id is "<<QThread::currentThreadId();
    ui->lineEdit_1->setText(str);
}



main.cpp

#include "widget.h"
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    qWarning()<<"main  id is "<<QThread::currentThreadId();
    return a.exec();
}



运行结果

在这里插入图片描述

Widget::Widget thread id is 0x7ffff7fba840

main id is 0x7ffff7fba840

Widget::Update_Result thread id is 0x7fffd18fd700

Widget::Update_Result thread id is 0x7fffd18fd700

Widget::Update_Result thread id is 0x7fffd18fd700

Widget::Update_Result thread id is 0x7fffd18fd700

Widget::Update_Result thread id is 0x7fffd18fd700

Widget::Update_Result thread id is 0x7fffd18fd700



版权声明:本文为zxgailixien原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。