Qt 多线程探秘2--Qt Concurrent

  很多东西存在很久但不切实使用并不能体会到它存在的深层的意义,往往这些是前人凝结出的精华而你的知识结构当前还不能体会。QFuture就是其中之一。
  Qt 多线程探秘1中使用QThread可以完成一个次线程执行的任务,虽然之需要少量的代码,这也是需要工作量的,要知道Qt其实早就有帮我们实现,这便是QFuture。
QFuture存在的意义应该就是能够便于监管线程(通过QFutureWatcher),这方面比较简单,不赘述,主要介绍如何实现探秘1中QThread完成的任务。于是就不得不引入QtConcurrent了(QFuture内部比较简单,应该一般不会主动new一个QFuture出来,而是通过QtConcurrent的静态方法产生一个QFuture,然后通过QFutureWatcher进行监控)。

  1. Concurrent Map and Map-Reduce
    QtConcurrent::map() applies a function to every item in a container, modifying the items in-place.
    QtConcurrent::mapped() is like map(), except that it returns a new container with the modifications.
    QtConcurrent::mappedReduced() is like mapped(), except that the modified results are reduced or folded into a single result.
  2. Concurrent Filter and Filter-Reduce
    QtConcurrent::filter() removes all items from a container based on the result of a filter function.
    QtConcurrent::filtered() is like filter(), except that it returns a new container with the filtered results.
    QtConcurrent::filteredReduced() is like filtered(), except that the filtered results are reduced or folded into a single result.
  3. Concurrent Run
    QtConcurrent::run() runs a function in another thread.

  主要有以上3中方法启动一个Future,其中:
a. 1将通过map函数多线程地执行容器中每个元素,其中map和maped的区别在于map将修改原始容器内对象,而maped将只能从QFuture::results()获取返回容器;最后一个mappedReduced,主要需要提供一个ReduceFunction 及QtConcurrent::ReduceOptions ,ReduceFunction 为一个合并函数,类似累加,QtConcurrent::ReduceOptions则告诉容器合并的顺序为无序添加还是有序添加;
b. 2提供多线程的容器过滤方法,具体函数意义与a类似;
c. 3提供直接在次线程运行某个方法的便捷的方式(这便是我说的比QThread更便利的实现,但是这和QThread也有一个缺陷,貌似每次只能随机指定一个线程,不能像QThread某个Thread代表某个固定的工作线程)。
上面三种方式,只有3是不能中途cancel的,其余均可通过QFuture或者QFutureWatcher进行cancel,pause等。
QtConcurrent中还有blockingFilter等用于当前线程阻塞等待Future执行完成。

  余下便是QFuture和结果相关的类

QFuture 代表异步计算
QFutureIterator QFuture结果的迭代器
QFutureWatcher QFuture的监视器
QFutureSynchronizer 自动同步多个QFuture的帮助类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值