百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

QtConcurrent 线程使用说明

bigegpt 2024-08-21 12:21 2 浏览

关于Qt Concurrent,我们首先来看看Qt Assitant是怎么描述的。

The QtConcurrent namespace provides high-level APIs that make it possible to write multi-threaded programs without using low-level threading primitives such as mutexes, read-write locks, wait conditions, or semaphores. Programs written with QtConcurrent automatically adjust the number of threads used according to the number of processor cores available. This means that applications written today will continue to scale when deployed on multi-core systems in the future.

说简单点,就是我们使用QtConcurrent 实现多线程时,可以不用考虑对共享数据的保护问题。而且,它可以根据CPU的能力,自动优化线程数。

QtConcurrent 主要提供了3种实现多线程的方法,分别是:run,map,filter。下面分别进行详细说明使用方法。

目录

  • Concurrent run,在线程池内起一个线程来执行一个函数。
  • Concurrent map, 用于并行处理一批数据的场景。
  • Concurrent Filter,顾名思义,一般用于对一批数据的过滤操作。

Qt资料领取:→Qt开发(视频教程+文档+代码+项目实战)

Concurrent run,在线程池内起一个线程来执行一个函数。基本用法如下:

extern void aFunction();
QFuture<void> future = QtConcurrent::run(aFunction);
//std::thread 实现
std::thread thread = std::thread(aFunction);
thread.detach();

如上,标准库的thread 也能实现相同功能。不同的是,QtConcurrent 实现的线程,可以获取到线程函数的返回值。

extern QString functionReturningAString();
QFuture<QString> future = QtConcurrent::run(functionReturningAString);
...
QString result = future.result();

QtConcurrent::run() 也提供了线程函数传参的实现:

extern QString someFunction(const QByteArray &input);
QByteArray bytearray = ...;
QFuture<QString> future = QtConcurrent::run(someFunction, bytearray);
...
QString result = future.result();

另外,同std::thread, QtConcurrent::run() 也提供了成员函数实现线程的方案。

1)调用const 函数

QByteArray bytearray = "hello world";
QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ',');

或,

QFuture<QList<QByteArray> > future = QtConcurrent::run(&bytearray, &QByteArray::split, ',');

2)调用非const 函数

QImage image = ...;
QFuture<void> future = QtConcurrent::run(&image, &QImage::invertPixels, QImage::InvertRgba);

Concurrent map, 用于并行处理一批数据的场景。主要包含map, mapped, mappedReduced 三种用法。

map 函数用于需要更改原数据的使用场景,使用方法如下:

void toUpper(QString &str)
{
    str = str.toUpper();
}
QStringList strWords;
strWords << "Apple" << "Banana" << "cow" << "dog" << "Egg";
auto future =  QtConcurrent::map(strWords, toUpper);
future.waitForFinished();
//strWords = {"APPLE", "BANANA", "COW", "DOG", "EGG"}

mapped 函数用于不改变原数据,返回处理结果的使用场景。使用方法如下:

QString toUpper(const QString &str)
{
    return str.toUpper();
}
QStringList strWords;
strWords << "Apple" << "Banana" << "cow" << "dog" << "Egg";
auto future =  QtConcurrent::mapped(strWords, toUpper);
future.waitForFinished();
qDebug() << future.results();
//输出:("APPLE", "BANANA", "COW", "DOG", "EGG")

mappedReduced 用于mapped处理后的结果还需要进行处理的使用场景。使用方法如下:

QString toUpper(const QString &str)
{
    return str.toUpper();
}
void reduceFun(QList<QString> &dictionary, const QString &string)
{
    dictionary.push_back(QString("result: ") + string);
}
 
QStringList strWords;
strWords << "Apple" << "Banana" << "cow" << "dog" << "Egg";
auto future =  QtConcurrent::mappedReduced(strWords, toUpper, reduceFun);
future.waitForFinished();
qDebug() << future.result();
//输出:("result: BANANA", "result: APPLE", "result: COW", "result: DOG", "result: EGG")

注意,上述代码输处结果的顺序与原数据的顺序已经不一样了。mappedReduced 函数的逻辑是,启动多个线程执行toUper 对链表中的每个元素进行处理,处理后的结果再逐一交给reduceFun函数处理。reduceFun 并不会等toUper的所有线程执行完毕后才开始执行,并且,同一时刻,只有一个reduceFun 线程在执行。如果需要使最后的输出结果顺序与输入相一致,就要用到mappedReduced 函数的第四个参数,赋值为QtConcurrent::OrderedReduce, 即可保证顺序一致。

同样的,Concurrent map也提供了成员函数作为线程函数的使用形式。线程函数必须是序列中元素的类型的成员函数。Qt 帮助文档中给出了如下示例:

// Squeeze all strings in a QStringList.
QStringList strings = ...;
QFuture<void> squeezedStrings = QtConcurrent::map(strings, &QString::squeeze);
 
// Swap the rgb values of all pixels on a list of images.
QList<QImage> images = ...;
QFuture<QImage> bgrImages = QtConcurrent::mapped(images, &QImage::rgbSwapped);
 
// Create a set of the lengths of all strings in a list.
QStringList strings = ...;
QFuture<QSet<int> > wordLengths = QtConcurrent::mappedReduced(strings, &QString::length, &QSet<int>::insert);

Concurrent map 还可以使用函数对象。Qt 帮助文档中给出了如下示例:

struct Scaled
{
    Scaled(int size): m_size(size) { }
    typedef QImage result_type;
 
    QImage operator()(const QImage &image)
    {
        return image.scaled(m_size, m_size);
    }
 
    int m_size;
};
 
QList<QImage> images = ...;
QFuture<QImage> thumbnails = QtConcurrent::mapped(images, Scaled(100));

Concurrent Filter,顾名思义,一般用于对一批数据的过滤操作。同样也包含filter, filtered, filteredReduce 三种用法。

filter 函数必须按如下形式定义,T类型与处理数据的元素类型一致,返回false时,过滤掉相应的元素。

bool function(const T &t);

与Concurrent map 类似,filter 函数会改变原始数据,filtered 函数将处理结果保存在filtered 函数的返回值中,filteredReduce 会将过滤后的数据再调用reduceFun 函数处理。这里就不再进行详细赘述,可以完全参考map函数的用法使用。

相关推荐

悠悠万事,吃饭为大(悠悠万事吃饭为大,什么意思)

新媒体编辑:杜岷赵蕾初审:程秀娟审核:汤小俊审签:周星...

高铁扒门事件升级版!婚宴上‘冲喜’老人团:我们抢的是社会资源

凌晨两点改方案时,突然收到婚庆团队发来的视频——胶东某酒店宴会厅,三个穿大红棉袄的中年妇女跟敢死队似的往前冲,眼瞅着就要扑到新娘的高额钻石项链上。要不是门口小伙及时阻拦,这婚礼造型团队熬了三个月的方案...

微服务架构实战:商家管理后台与sso设计,SSO客户端设计

SSO客户端设计下面通过模块merchant-security对SSO客户端安全认证部分的实现进行封装,以便各个接入SSO的客户端应用进行引用。安全认证的项目管理配置SSO客户端安全认证的项目管理使...

还在为 Spring Boot 配置类加载机制困惑?一文为你彻底解惑

在当今微服务架构盛行、项目复杂度不断攀升的开发环境下,SpringBoot作为Java后端开发的主流框架,无疑是我们手中的得力武器。然而,当我们在享受其自动配置带来的便捷时,是否曾被配置类加载...

Seata源码—6.Seata AT模式的数据源代理二

大纲1.Seata的Resource资源接口源码2.Seata数据源连接池代理的实现源码3.Client向Server发起注册RM的源码4.Client向Server注册RM时的交互源码5.数据源连接...

30分钟了解K8S(30分钟了解微积分)

微服务演进方向o面向分布式设计(Distribution):容器、微服务、API驱动的开发;o面向配置设计(Configuration):一个镜像,多个环境配置;o面向韧性设计(Resista...

SpringBoot条件化配置(@Conditional)全面解析与实战指南

一、条件化配置基础概念1.1什么是条件化配置条件化配置是Spring框架提供的一种基于特定条件来决定是否注册Bean或加载配置的机制。在SpringBoot中,这一机制通过@Conditional...

一招解决所有依赖冲突(克服依赖)

背景介绍最近遇到了这样一个问题,我们有一个jar包common-tool,作为基础工具包,被各个项目在引用。突然某一天发现日志很多报错。一看是NoSuchMethodError,意思是Dis...

你读过Mybatis的源码?说说它用到了几种设计模式

学习设计模式时,很多人都有类似的困扰——明明概念背得滚瓜烂熟,一到写代码就完全想不起来怎么用。就像学了一堆游泳技巧,却从没下过水实践,很难真正掌握。其实理解一个知识点,就像看立体模型,单角度观察总...

golang对接阿里云私有Bucket上传图片、授权访问图片

1、为什么要设置私有bucket公共读写:互联网上任何用户都可以对该Bucket内的文件进行访问,并且向该Bucket写入数据。这有可能造成您数据的外泄以及费用激增,若被人恶意写入违法信息还可...

spring中的资源的加载(spring加载原理)

最近在网上看到有人问@ContextConfiguration("classpath:/bean.xml")中除了classpath这种还有其他的写法么,看他的意思是想从本地文件...

Android资源使用(android资源文件)

Android资源管理机制在Android的开发中,需要使用到各式各样的资源,这些资源往往是一些静态资源,比如位图,颜色,布局定义,用户界面使用到的字符串,动画等。这些资源统统放在项目的res/独立子...

如何深度理解mybatis?(如何深度理解康乐服务质量管理的5个维度)

深度自定义mybatis回顾mybatis的操作的核心步骤编写核心类SqlSessionFacotryBuild进行解析配置文件深度分析解析SqlSessionFacotryBuild干的核心工作编写...

@Autowired与@Resource原理知识点详解

springIOCAOP的不多做赘述了,说下IOC:SpringIOC解决的是对象管理和对象依赖的问题,IOC容器可以理解为一个对象工厂,我们都把该对象交给工厂,工厂管理这些对象的创建以及依赖关系...

java的redis连接工具篇(java redis client)

在Java里,有不少用于连接Redis的工具,下面为你介绍一些主流的工具及其特点:JedisJedis是Redis官方推荐的Java连接工具,它提供了全面的Redis命令支持,且...