Qt文档阅读笔记-QThreadPool官方解析及实例
QThreadPool管理及回收QThread对象,用来减少线程创建时带来的系统开销。每一个Qt进程都有个全局的QThreadPool对象,可以通过globalInstance()获取其对象。
要想使用QThreadPool中的线程,需要先创建一个类,这个类继承QRunnable,并且要重写其run()方法。随后创建其对象,调用QThreadPool::start()方法,如下实例代码:
class HelloWorldTask : public QRunnable
{
void run() override
{
qDebug() << "Hello world from thread" << QThread::currentThread();
}
};
HelloWorldTask *hello = new HelloWorldTask();
// QThreadPool takes ownership and deletes 'hello' automatically
QThreadPool::globalInstance()->start(hello);
QThreadPool会自动释放QRunnable的子类,使用QRunnable::setAutoDelete()改变auto-deletion标识。
QThreadPool支持多次执行相同的QRunnable线程。这里推荐使用tryStart(this)。当最后一个线程执行结束,QRunnable就会被自动释放掉。
启用autoDelete后,调用start()多次启动相同的进程时,会形成竞争条件,不建议这么使用。
在一定时间内未被使用的线程会过期,默认是30s,可以通过setExpiryTimeout()来设置。
setMaxThreadCount()设置最大线程数maxThreadCount()用于查询.
maxThreadCount()的默认值为QThread::idealThreadCount(),activeThreadCount()返回当前正在工作的线程数。
reserveThread()函数是在线程外使用的。当调用releaseThread()来释放线程时,这个线程可能会被重复利用,这时reserveThread()就可以得到releaThread()的那个线程。
下面是自己写的一个小栗子
功能是这样的:
写一个线程,这个线程放到QThreadPool,里面,并且线程池每秒调用一次,QThreadPool里面的线程,把当前时间发送给主线程。然后打印。
还是有点意思的!
程序运行截图如下:
源码如下:
Com.h
#ifndef COM_H
#define COM_H
#include <QObject>
QT_BEGIN_NAMESPACE
class QThreadPool;
class QTimer;
QT_END_NAMESPACE
class Com : public QObject
{
Q_OBJECT
public:
Com(QObject *parent = nullptr);
protected slots:
void timeOut();
void getTime(const QString &time);
private:
QThreadPool *m_pool;
QTimer *m_timer;
};
#endif // COM_H
Woork.h
#ifndef WORK_H
#define WORK_H
#include <QObject>
#include <QRunnable>
class Work : public QObject, public QRunnable
{
Q_OBJECT
public:
Work();
~Work();
protected:
void run() Q_DECL_OVERRIDE;
signals:
void nowTime(const QString &time);
};
#endif // WORK_H
Com.cpp
#include "Com.h"
#include "Woork.h"
#include <QTimer>
#include <QThreadPool>
#include <QDebug>
Com::Com(QObject *parent) : QObject(parent)
{
m_timer = new QTimer(this);
m_pool = new QThreadPool(this);
m_pool->setMaxThreadCount(1);
connect(m_timer, &QTimer::timeout, this, &Com::timeOut);
m_timer->start(1000);
}
void Com::timeOut()
{
Work *work = new Work;
connect(work, &Work::nowTime, this, &Com::getTime);
m_pool->start(work);
}
void Com::getTime(const QString &time)
{
qDebug() << "接收到:" + time;
}
main.cpp
#include <QCoreApplication>
#include "Com.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Com com;
return a.exec();
}
Woork.cpp
#include "Woork.h"
#include <QDateTime>
#include <QDebug>
Work::Work()
{
qDebug() << "Work::Work()";
}
Work::~Work()
{
qDebug() << "Work::~Work()";
}
void Work::run()
{
emit this->nowTime(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
}
源码打包下载地址:
https://github.com/fengfanchen/Qt/tree/master/QThreadPoolDemo
还没有评论,来说两句吧...