一、concurrent.futures模块简介

concurrent.futures 模块提供了并发执行调用的高级接口

并发可以使用threads执行,使用ThreadPoolExecutor 或 分离的processes,使用ProcessPoolExecutor。都实现了同一个接口,这个接口在抽象类Executor定义

二、类的属性和方法

concurrent.futures.wait(fstimeout=Nonereturn_when=ALL_COMPLETED):wait等待fs里面所有的Future实例(由不同的Executors实例创建的)完成。返回两个命名元祖,第一个元祖名为done,存放完成的futures对象,第二个元祖名为not_done,存放未完成的futures。return_when参数必须是concurrent.futures里面定义的常量:FIRST_COMPLETED,FIRST_EXCEPTION,ALL_COMPLETED

concurrent.futures.as_completed(fstimeout=None):返回一个迭代器,yield那些完成的futures对象。fs里面有重复的也只可能返回一次。任何futures在调用as_completed()调用之前完成首先被yield。

三、Future对象

Future()封装了可调用对象的异步执行。Future实例可以被Executor.submit()方法创建。除了测试之外不应该直接创建。Future对象可以和异步执行的任务进行交互

cancel():尝试去取消调用。如果调用当前正在执行,不能被取消。这个方法将返回False,否则调用将会被取消,方法将返回True

cancelled():如果调用被成功取消返回True

running():如果当前正在被执行不能被取消返回True

done():如果调用被成功取消或者完成running返回True

result(Timeout = None):拿到调用返回的结果。如果没有执行完毕就会去等待

exception(timeout=None):捕获程序执行过程中的异常

add_done_callback(fn):将fn绑定到future对象上。当future对象被取消或完成运行时,fn函数将会被调用

以下的方法是在unitest中

set_running_or_notify_cancel()

set_result(result)

set_exception(exception) 

Future方法

四、Executor对象

1、抽象类,提供异步调用的方法。不能被直接使用,而是通过构建子类。

2、方法

提交任务方式一:submit(fn*args**kwargs):调度函数fn(*args **kwargs)返回一个Future对象代表调用的执行。

提交任务方式二:map(func*iterablestimeout=Nonechunksize=1):和map(func, *iterables)相似。但是该map方法的执行是异步的。多个func的调用可以同时执行。当Executor对象是 ProcessPoolExecutor,才可以使用chunksize,将iterable对象切成块,将其作为分开的任务提交给pool,默认为1。对于很大的iterables,设置较大chunksize可以提高性能(切记)。

shutdown(wait=True):给executor发信号,使其释放资源,当futures完成执行时。已经shutdown再调用submit()或map()会抛出RuntimeError。使用with语句,就可以避免必须调用本函数

五、ThreadPoolExecutor对象

ThreadPoolExecutor是Executor的子类使用线程池来异步执行调用

如果使用不正确可能会造成死锁,所以submit的task尽量不要调用executor和futures,否则很容易出现死锁

import time
def wait_on_b():
time.sleep(5)
print(b.result()) # b will never complete because it is waiting on a.
return 5 def wait_on_a():
time.sleep(5)
print(a.result()) # a will never complete because it is waiting on b.
return 6 executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)

相互等待的死锁

def wait_on_future():
f = executor.submit(pow, 5, 2)
# This will never complete because there is only one worker thread and
# it is executing this function.
print(f.result()) executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)

等待自己的结果的死锁

默认的max_workers是设备的处理器数目*5

六、ProcessPoolExecutor对象

ProcessPoolExecutor同样是Executor的子类。使用进程池来异步执行调用。

Executor.submit() called:
- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict
- adds the id of the _WorkItem to the "Work Ids" queue Local worker thread:
- reads work ids from the "Work Ids" queue and looks up the corresponding
WorkItem from the "Work Items" dict: if the work item has been cancelled then
it is simply removed from the dict, otherwise it is repackaged as a
_CallItem and put in the "Call Q". New _CallItems are put in the "Call Q"
until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because
calls placed in the "Call Q" can no longer be cancelled with Future.cancel().
- reads _ResultItems from "Result Q", updates the future stored in the
"Work Items" dict and deletes the dict entry Process #1..n:
- reads _CallItems from "Call Q", executes the calls, and puts the resulting
_ResultItems in "Result Q"

数据流程解释

ProcessPoolExecutor使用multiprocessing模块,不受GIL锁的约束,意味着只有可以pickle的对象才可以执行和返回(pickle参考)

__main__必须能够被工作子进程导入。所以意味着ProcessPoolExecutor在交互式解释器下不能工作。

提交给ProcessPoolExecutor的可调用方法里面调用Executor或Future将会形成死锁。

class concurrent.futures.ProcessPoolExecutor(max_workers=None)

max_workers默认是处理器的个数

import concurrent.futures
import math PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
115797848077098,
1099726899285419] def is_prime(n):
"""
to judge the input number is prime or not
:param n: input number
:return: True or False
"""
if n % 2 == 0:
return False sqrt_n = int(math.(math.sqrt(n)))
for i in range(3,sqrt_n + 1, 2):
if n % i == 0:
return False
return True def main():
"""
create Process Pool to judge the numbers is prime or not
:return: None
"""
with concurrent.futures.ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print(number,prime) if __name__ == '__main__':
main()

样例

七、Exception类

exception concurrent.futures.CancelledError

exception concurrent.futures.TimeoutError

exception concurrent.futures.process.BrokenProcessPool

python之concurrent.futures模块的更多相关文章

  1. Python之concurrent.futures模块的使用

    concurrent.futures的作用:       管理并发任务池.concurrent.futures模块提供了使用工作线程或进程池运行任务的接口.线程和进程池API都是一样,所以应用只做最小 ...

  2. Python之线程 3 - 信号量、事件、线程队列与concurrent.futures模块

    一 信号量 二 事件 三 条件Condition 四 定时器(了解) 五 线程队列 六 标准模块-concurrent.futures 基本方法 ThreadPoolExecutor的简单使用 Pro ...

  3. Python并发编程之线程池/进程池--concurrent.futures模块

    一.关于concurrent.futures模块 Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/ ...

  4. 《转载》Python并发编程之线程池/进程池--concurrent.futures模块

    本文转载自Python并发编程之线程池/进程池--concurrent.futures模块 一.关于concurrent.futures模块 Python标准库为我们提供了threading和mult ...

  5. Python之路(第四十六篇)多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)

    一.线程池 很久(python2.6)之前python没有官方的线程池模块,只有第三方的threadpool模块, 之后再python2.6加入了multiprocessing.dummy 作为可以使 ...

  6. Python之网络编程之concurrent.futures模块

    需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...

  7. 45、concurrent.futures模块与协程

    concurrent.futures  —Launching parallel tasks    concurrent.futures模块同时提供了进程池和线程池,它是将来的使用趋势,同样我们之前学习 ...

  8. 线程池、进程池(concurrent.futures模块)和协程

    一.线程池 1.concurrent.futures模块 介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 Pro ...

  9. 35、concurrent.futures模块与协程

    concurrent.futures  —Launching parallel tasks    concurrent.futures模块同时提供了进程池和线程池,它是将来的使用趋势,同样我们之前学习 ...

随机推荐

  1. php 7.2 安装 mcrypt 扩展: mcrypt 扩展从 php 7.1.0 开始废弃;自 php 7.2.0 起,会移到 pecl

    升级 php 7.2 后,使用微信提供的加解密代码时,提示 call to undefined function mcrypt_module_open() :大脑疯狂运转1秒钟后,得出结论:php 7 ...

  2. [Java学习] Java多态和动态绑定

    在Java中,父类的变量可以引用父类的实例,也可以引用子类的实例. 请读者先看一段代码: 1. public class Demo { 2. public static void main(Strin ...

  3. 词向量-LRWE模型-更好地识别反义词同义词

    上一节,我们介绍利用文本和知识库融合训练词向量的方法,如何更好的融合这些结构化知识呢?使得训练得到的词向量更具有泛化能力,能有效识别同义词反义词,又能学习到上下文信息还有不同级别的语义信息. 基于上述 ...

  4. 新概念 Lesson 2 Sorry, sir.

    Is this your handbag? 这是你的手提包吗? Yes,it is. /No it isn't 人称代词的主格宾格 形容性物主代词的用法 Does the man get his um ...

  5. android--------阿里 AndFix 热修复

    AndFix,全称是Android hot-fix.是阿里开源的一个热补丁框架,允许APP在不重新发布版本的情况下修复线上的bug. 支持Android 2.3 到 6.0,并且支持arm 与 X86 ...

  6. Confluence 6 的 Crowd 权限

    只读(Read Only) 从 Crowd 上获取的用户,用户组和用户组成员信息只具有读取权限,你只能在 Crowd 上对你的配置进行修改.你不能通过你的应用程序管理员界面修改,用户,用户组,用足成员 ...

  7. 百度安卓SDK秘钥Key错误

    下载官方安卓地图demo,输入报名和sha1申请AK,发现key错误 构建的时候要指定生成的key 安卓定位BaiduLocDemo出现aapt.exe finished with non-zero ...

  8. Axel and Marston in Bitland CodeForces - 782F (bitset优化)

    题目链接 $dp[0/1][i][x][y]$表示起始边为0/1, 走$2^i$ 步, 是否能从$x$走到$y$ 则有转移方程 $dp[z][i][x][y]\mid=dp[z][i-1][x][k] ...

  9. hdu2087kmp

    一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案.对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?  Input输入中含有一些数据,分别是成对出现的花布条和 ...

  10. python-day18--匿名函数

    一.lambda表达式 1.匿名函数的核心:一些简单的需要用函数去解决的问题,匿名函数的函数体只有一行 2.参数可以有多个,用逗号隔开 3.返回值和正常的函数一样可以是任意的数据类型 4.练习: 请把 ...