Qt多线程-QThreadPool线程池与QRunnable
本文标题:Qt多线程-QThreadPool线程池与QRunnable 本文地址:https://www.techieliang.com/2017/12/605/
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?<i>msecs</i>?=?-1)//等待所有线程运行结束并退出,参数为等待时间-1表示一直等待到最后一个线程退出
QThread::idealThreadCount函数,会根据当前设备的硬件情况给出一个线程数量,而maxThreadCount的默认值就是此值。
setStackSize
只有在线程池创建新线程时才使用该属性的值。更改它对已经创建或运行的线程没有影响。默认值是0,这使得qthread使用操作系统默认的堆栈大小。
The value of the property is only used when the thread
pool creates new threads. Changing it has no effect for already created
or running threads.The default value is 0, which makes QThread use the operating system default stack size.
maxThreadCount? reserveThread? activeThreadCount
由于reserveThread 后的线程不计入线程数量,因此可能出现activeThreadCount>maxThreadCount? 情况
Note: It is possible for this function to return a value that is greater than maxThreadCount(). See reserveThread() for more details.
2.2. start tryStart tryTake
对于start,传入的是QRunnable对象指针,传入后线程池会调用QRunnable的autoDelete() 函数,若返回true,则当此运算完成后自动释放内容,不需要后续主动判断是否运算完成并释放空间。
对于tryTake,若返回成功,不会自动释放内容,而是需要调用方主动释放,无论autodelete返回值是什么。返回false自然也不会自动delete
Attempts to remove the specified runnable from the queue if it is not yet started. If the runnable had not been started, returns
true
, and ownership of runnable is transferred to the caller (even whenrunnable->autoDelete() == true
). Otherwise returnsfalse
.Note: If
runnable->autoDelete() == true
, this function may remove the wrong runnable. This is known as the ABA problem: the original runnable
may already have executed and has since been deleted. The memory is
re-used for another runnable, which then gets removed instead of the
intended one. For this reason, we recommend calling this function only
for runnables that are not auto-deleting.
对于tryStart,若返回成功,等同于start,若false,则不会自动delete
注意,对于autoDelete必须在调用state/trytake之前进行修改,不要再调用以后修改,否则结果不可预测
Note that changing the auto-deletion on runnable after calling this function results in undefined behavior.
QRunnable的autoDelete默认返回true,若需要更改需要调用setAutoDelete进行更改
2.3. 全局线程池
QThreadPool提供了一个静态函数,globalInstance(),使用此方法可获取一个当前进程的全局线程池,可在多个类中共同使用一个线程池。
2.4. 局部线程池
和常规类的使用相同,可以通过? 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. 范例
4.1. 简单使用范例
- #include <QCoreApplication>
- #include <QThreadPool>
- #include <QThread>
- #include <QRunnable>
- #include <QDebug>
- class MyRun : public QRunnable {
- public:
- void run() {
- int i=3;
- while(i) {
- i--;
- qDebug()<<"thread start:"<<QThread::currentThreadId();
- QThread::msleep(500);
- }
- }
- };
- int main(int argc, char *argv[]) {
- QCoreApplication a(argc, argv);
- qDebug()<<"Main:"<<QThread::currentThreadId();
- QThreadPool m;
- MyRun *run=new MyRun;
- if(!run->autoDelete()) {
- qDebug()<<"QRunnable's autoDelete default value is not true";
- run->setAutoDelete(true);
- }
- qDebug()<<m.maxThreadCount()<<m.expiryTimeout();
- qDebug()<<m.activeThreadCount();
- m.start(run);
- qDebug()<<m.activeThreadCount();
- m.waitForDone();
- qDebug()<<m.activeThreadCount();
- return 0;
- }
结果:
- Main: 0xffc
- 4 30000
- 0
- 1
- thread start: 0x7e4
- thread start: 0x7e4
- thread start: 0x7e4
- 0
4.2. 全局线程池和局部线程池对比
- #include <QCoreApplication>
- #include <QThreadPool>
- #include <QThread>
- #include <QRunnable>
- #include <QDebug>
- class MyRun : public QRunnable {
- public:
- void run() {
- int i=3;
- while(i) {
- i--;
- qDebug()<<"thread start:"<<QThread::currentThreadId();
- QThread::msleep(500);
- }
- }
- };
- int main(int argc, char *argv[]) {
- QCoreApplication a(argc, argv);
- qDebug()<<"Main:"<<QThread::currentThreadId();
- QThreadPool pool;
- QThreadPool *global_pool = QThreadPool::globalInstance();
- MyRun *run=new MyRun;
- if(!run->autoDelete()) {
- qDebug()<<"QRunnable's autoDelete default value is not true";
- run->setAutoDelete(true);
- }
- pool.setMaxThreadCount(2);//修改了局部线程数量
- qDebug()<<"pool:"<<pool.maxThreadCount()<<pool.expiryTimeout()<<"\r\nglobal"<<global_pool->maxThreadCount();
- qDebug()<<pool.activeThreadCount()<<global_pool->activeThreadCount();
- pool.start(run);
- global_pool->start(new MyRun);
- qDebug()<<pool.activeThreadCount()<<global_pool->activeThreadCount();
- pool.waitForDone();
- global_pool->waitForDone();
- qDebug()<<pool.activeThreadCount()<<global_pool->activeThreadCount();
- return 0;
- }
结果
- Main: 0x30c4
- pool: 2 30000
- global 4
- 0 0
- 1 1
- thread start: 0x22d0
- thread start: 0xfe0
- thread start: 0x22d0
- thread start: 0xfe0
- thread start: 0x22d0
- thread start: 0xfe0
- 0 0
当建立局部线程池,修改其参数后仅供局部使用,不会影响全局线程池的。
Qt多线程-QThreadPool线程池与QRunnable的更多相关文章
- Qt中的多线程与线程池浅析+实例
1. Qt中的多线程与线程池 今天学习了Qt中的多线程和线程池,特写这篇博客来记录一下 2. 多线程 2.1 线程类 QThread Qt 中提供了一个线程类,通过这个类就可以创建子线程了,Qt 中一 ...
- C#多线程之线程池篇3
在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...
- C#多线程之线程池篇2
在上一篇C#多线程之线程池篇1中,我们主要学习了如何在线程池中调用委托以及如何在线程池中执行异步操作,在这篇中,我们将学习线程池和并行度.实现取消选项的相关知识. 三.线程池和并行度 在这一小节中,我 ...
- C#多线程之线程池篇1
在C#多线程之线程池篇中,我们将学习多线程访问共享资源的一些通用的技术,我们将学习到以下知识点: 在线程池中调用委托 在线程池中执行异步操作 线程池和并行度 实现取消选项 使用等待句柄和超时 使用计时 ...
- 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法
[源码下载] 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法 作者:webabcd 介绍重新想象 Wi ...
- ExecutorService 建立一个多线程的线程池的步骤
ExecutorService 建立一个多线程的线程池的步骤: 线程池的作用: 线程池功能是限制在系统中运行的线程数. 依据系统的环境情况,能够自己主动或手动设置线程数量.达到执行的最佳效果:少了浪费 ...
- C#多线程和线程池问题
static void Main(string[] args) { Thread threadA = new Thread(ThreadMethod); //执行的必须是无返回值的方法 threadA ...
- Java基础教程:多线程基础——线程池
Java基础教程:多线程基础——线程池 线程池 在正常负载的情况瞎,通过为每一个请求创建一个新的线程来提供服务,从而实现更高的响应性. new Thread(runnable).start() 在生产 ...
- Python多线程、线程池及实际运用
我们在写python爬虫的过程中,对于大量数据的抓取总是希望能获得更高的速度和效率,但由于网络请求的延迟.IO的限制,单线程的运行总是不能让人满意.因此有了多线程.异步协程等技术. 下面介绍一下pyt ...
随机推荐
- 【python安装】Windows上安装和创建python开发环境
1. 在 windows10 上安装python开发环境 Linux和Mac OS都自带python环境,但是Windows没有,所以需要自行安装. 第1步:访问 python官网,下载Windows ...
- My First
刚入职不到2个月吧,还在实习,月底拿毕业证转正.工作期间遇到很多麻烦问题,有的解决了,有的解决不了,换了个方法实现,挺无奈的.弄个博客,记录下平常遇到的问题和解决方式,也省的每次拿个笔记下来了…… 公 ...
- scala (5) 可变序列和不可变序列
/** * 序列分为可变长和不可变长,序列其实就是list,底层是链表结构 * 特点:插入有序,可重复,增加和移除元素很快,查询慢 * 不可变长序列:List * 可变长序列:ListBuffer * ...
- HyperLedger Fabric 1.4 区块链技术原理(2.2)
区块链从字面上理解:数据记录在区块中,通过一定的算法把区块连成一个链. 区块链通过哈希(Hash)算法,生成一串字符串,保存在区块的头部中,一个的区块通过指向上一个Hash值,加入到区块链 ...
- 20155306 实验四 Android程序设计
20155306 实验四 Android程序设计 实验内容 1.基于Android Studio开发简单的Android应用并部署测试; 2.了解Android.组件.布局管理器的使用: 3.掌握An ...
- 学号20155308 2006-2007-2 《Java程序设计》第3周学习总结
学号20155308 2006-2007-2 <Java程序设计>第3周学习总结 教材学习内容总结 对象(Object):存在的具体实体,具有明确的状态和行为 类(Class):具有相同属 ...
- WPF 带刻度的滑动条实现
原文:WPF 带刻度的滑动条实现 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/BYH371256/article/details/83507170 ...
- jsp命名规则
jsp也用驼峰规则命名即可,不要使用下划线,否则在tomcat中容易出现解析错误
- js中对象转化成字符串、数字或布尔值的转化规则
js中对象可以转化成 字符串.数字.布尔值 一.对象转化成字符串: 规则: 1.如果对象有toString方法,则调用该方法,并返回相应的结果:(代码通常会执行到这,因为在所有对象中都有toStrin ...
- 423. Valid Parentheses【LintCode java】
Description Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine ...