第十七章:并发处理

本章主要讨论Python3引入的concurrent.futures模块。在python2.7中需要用pip install futures来安装。concurrent.futures 是python3新增加的一个库,用于并发处理,提供了多线程和多进程的并发功能 类似于其他语言里的线程池(也有一个进程池),他属于上层的封装,对于用户来说,不用在考虑那么多东西了。

使用方法:
1 Executor:两个子类ThreadPoolExecutor和ProcessPoolExecutor分别是线程和进程
submit(fn,*args,**kwargs): fn是需要异步执行的函数,args,kwargs为给函数传递的参数

2 map(func, *iterables, timeout=None) 
此map函数和Python自带的map函数功能类似,只不过concurrent模块的map函数从迭代器获得参数后异步执行。并且,每一个异步操作,能用timeout参数来设置超时时间,timeout的值可以是int或float型,如果操作timeout的话,会raisesTimeoutError。如果timeout参数不指定的话,则不设置超时间。 
func:为需要异步执行的函数 
iterables:可以是一个能迭代的对象,例如列表等。每一次func执行,会从iterables中取参数。 
timeout:设置每次异步操作的超时时间

3 Future: Future实例是由Executor.submit()创建的。Future提供了丰富的方法来处理调用。

Future.cancel: 用cancel(),可以终止某个线程和进程的任务,返回状态为 True False

Future.cancelled():判断是否真的结束了任务。

Future.running():判断是否还在运行

Future.done():判断是正常执行完毕的。

Future.result(timeout=None): 针对result结果做超时的控制。

4 Wait: wait方法接会返回一个tuple(元组),tuple中包含两个set(集合),一个是completed(已完成的)另外一个是uncompleted(未完成的)。使用wait方法的一个优势就是获得更大的自由度,它接收三个参数FIRST_COMPLETED, FIRST_EXCEPTION和ALL_COMPLETE,默认设置为ALL_COMPLETED。三个参数的意义分别如下:

FIRST_COMPLETED - Return when any future finishes or is
                  cancelled.
FIRST_EXCEPTION - Return when any future finishes by raising an
                  exception. If no future raises an exception
                  then it is equivalent to ALL_COMPLETED.
ALL_COMPLETED -   Return when all futures finish or are cancelled.

下面来看一个实际的例子:

def caculate_value_by_wait(x):
    time.sleep(1)
    print 'The value of x*x=%d' % (x*x) if __name__=="__main__":
    num=[1,2,3,4,5,6]
    start_time=time.clock()
    for n in num:
        caculate_value_by_wait(n)     (1)
    print 'The toal time is %d' % (time.clock()-start_time)
    start_time1=time.clock()
    with futures.ThreadPoolExecutor(max_workers=6) as executor: (2)
        for n in num:
            executor.submit(caculate_value_by_wait,n)
    print 'Thread pool consume time is %d' % (time.clock()-start_time1)
    start_time2=time.clock()
    with futures.ProcessPoolExecutor(max_workers=6) as executor: (3)
        for n in num:
            executor.submit(caculate_value_by_wait,n)
    print 'Process pool consume time is %d' % (time.clock()-start_time2)

在这个例子中,分别用线性,多线程和多进程执行了caculate_value_by_wait。执行结果如下:在caculate_value_by_wait中每一次操作都会等待1秒。因此线性的执行总的时间为6秒。而多线程和多进程执行则总共耗时1秒

E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter17.py

The value of x*x=1

The value of x*x=4

The value of x*x=9

The value of x*x=16

The value of x*x=25

The value of x*x=36

The toal time is 6

The value of x*x=4

The value of x*x=1

The value of x*x=9

The value of x*x=16

The value of x*x=25The value of x*x=36

Thread pool consume time is 1

The value of x*x=1

The value of x*x=4

The value of x*x=9

The value of x*x=16

The value of x*x=25

The value of x*x=36

Process pool consume time is 1

如果是用map函数来改造的话,可以写成如下:

with futures.ProcessPoolExecutor(max_workers=6) as executor:
    executor.map(caculate_value_by_wait,num)
 
在上面的多线程或者多进程中,我们还可以进一步对每个线程进行监控。方法就是用Future。代码如下
def caculate_value_by_wait(x):
    time.sleep(1)
    return x*x if __name__=="__main__":
    num=[1,2,3,4,5,6]
    with futures.ThreadPoolExecutor(max_workers=6) as executor:
        future_task=[executor.submit(caculate_value_by_wait,n) for n in num]   (1)
        for f in future_task:
            if f.running():    (2)
                print '%s is running' % str(f)
        for f in as_completed(future_task):   (3)
            try:
                ret=f.done()                 (4)
                if ret:
                    f_ret=f.result()          (5)
                    print '%s done,result is %s' % (str(f),str(f_ret))
            except BaseException,e:
                f.cancel()
                print e
(1)  future_task得到所有运行的实例对象
(2)  判断线程是否在运行
(3)  得到完成线程的列表
(4)  判断是否真的完成,是返回True,否则返回False
(5)  得到各个线程返回的对象
得到的结果如下:
E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter17.py
<Future at 0x17cfed0 state=running> is running
<Future at 0x17d9050 state=running> is running
<Future at 0x17d9210 state=running> is running
<Future at 0x17d93d0 state=running> is running
<Future at 0x17d9590 state=running> is running
<Future at 0x17d9750 state=running> is running
<Future at 0x17d9210 state=finished returned int> done,result is 9
<Future at 0x17cfed0 state=finished returned int> done,result is 1
<Future at 0x17d93d0 state=finished returned int> done,result is 16
<Future at 0x17d9050 state=finished returned int> done,result is 4
<Future at 0x17d9750 state=finished returned int> done,result is 36
<Future at 0x17d9590 state=finished returned int> done,result is 25

再来看下wait的用法:

if __name__=="__main__":
    num=[1,2,3,4,5,6]
    with futures.ThreadPoolExecutor(max_workers=6) as executor:
        future_task=[executor.submit(caculate_value_by_wait,n) for n in num]
        for f in future_task:
            if f.running():
                print '%s is running' % str(f)
        results=wait(future_task)   (1)
        done=results[0]   (2)
        not_done=results[1]     (3)
        print 'The threads that have finished %s' % done
        print 'The threads that not have finished %s' % not_done
        for x in done:
            print x
        for y in not_done:
            print y

(1)    得到所有的线程

(2)    得到已完成的线程

(3)    得到未完成的线程

运行结果如下:

E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter17.py

<Future at 0x177def0 state=running> is running

<Future at 0x1788070 state=running> is running

<Future at 0x1788230 state=running> is running

<Future at 0x17883f0 state=running> is running

<Future at 0x17885b0 state=running> is running

<Future at 0x1788770 state=running> is running

The threads that have finished set([<Future at 0x1788230 state=finished returned int>, <Future at 0x1788070 state=finished returned int>, <Future at 0x177def0 state=finished returned int>, <Future at 0x1788770 state=finished returned int>, <Future at 0x17885b0 state=finished returned int>, <Future at 0x17883f0 state=finished returned int>])

The threads that not have finished set([])

<Future at 0x1788230 state=finished returned int>

<Future at 0x1788070 state=finished returned int>

<Future at 0x177def0 state=finished returned int>

<Future at 0x1788770 state=finished returned int>

<Future at 0x17885b0 state=finished returned int>

<Future at 0x17883f0 state=finished returned int>

流畅python学习笔记:第十七章:并发处理的更多相关文章

  1. #Python学习笔记:1-3章 (基于《python编程,从入门到实践)

    第1-3章 这个文档是记录我学习python时一些学习笔记以及一些想法也可以称作复习笔记 第一章:起步这一章主要是从第一个"hello world"程序到python环境的搭建与配 ...

  2. [Python学习笔记][第七章Python文件操作]

    2016/1/30学习内容 第七章 Python文件操作 文本文件 文本文件存储的是常规字符串,通常每行以换行符'\n'结尾. 二进制文件 二进制文件把对象内容以字节串(bytes)进行存储,无法用笔 ...

  3. [Python学习笔记][第五章Python函数设计与使用]

    2016/1/29学习内容 第四章 Python函数设计与使用 之前的几页忘记保存了 很伤心 变量作用域 -一个变量已在函数外定义,如果在函数内需要修改这个变量的值,并将这个赋值结果反映到函数之外,可 ...

  4. [Python学习笔记][第四章Python字符串]

    2016/1/28学习内容 第四章 Python字符串与正则表达式之字符串 编码规则 UTF-8 以1个字节表示英语字符(兼容ASCII),以3个字节表示中文及其他语言,UTF-8对全世界所有国家需要 ...

  5. [汇编学习笔记][第十七章使用BIOS进行键盘输入和磁盘读写

    第十七章 使用BIOS进行键盘输入和磁盘读写 17.1 int 9 中断例程对键盘输入的处理 17.2 int 16 读取键盘缓存区 mov ah,0 int 16h 结果:(ah)=扫描码,(al) ...

  6. 流畅python学习笔记:第十七章:并发处理二

    本章讨论python3.2引入的concurrent.futures模块.future是中文名叫期物.期物是一种对象,表示异步执行的操作 在很多任务中,特别是处理网络I/O.需要使用并发,因为网络有很 ...

  7. 流畅的python学习笔记:第二章

    第二章开始介绍了列表这种数据结构,这个在python是经常用到的结构 列表的推导,将一个字符串编程一个列表,有下面的2种方法.其中第二种方法更简洁.可读性也比第一种要好 str='abc' strin ...

  8. 流畅的python学习笔记:第一章

    这一章中作者简要的介绍了python数据模型,主要是python的一些特殊方法.比如__len__, __getitem__. 并用一个纸牌的程序来讲解了这些方法 首先介绍下Tuple和nametup ...

  9. 流畅python学习笔记:第十一章:抽象基类

    __getitem__实现可迭代对象.要将一个对象变成一个可迭代的对象,通常都要实现__iter__.但是如果没有__iter__的话,实现了__getitem__也可以实现迭代.我们还是用第一章扑克 ...

随机推荐

  1. 【LeetCode】144. Binary Tree Preorder Traversal

    题目: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binar ...

  2. Ubantu 16.4 samba安装配置

    本文总结了Ubantu 16.04 环境下的samba安装.配置及使用.本文为原创,也是我的第一篇博客,以后会经常写博客,记录自己的学习.总结及研究,让博客见证着我成长的轨迹. 下文中的所有命令均使用 ...

  3. JavaScript从入门到忘记

    JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的处理. 一.如何编写 二.变 ...

  4. JDBC02 利用JDBC连接数据库【使用数据库连接池】

    目录 1/2/3  Statement 和 Preparedstatement 的区别 4 读取properties配置文件 5 数据库连接池 6 利用数据库连接池连接数据库 1 使用Statemen ...

  5. 高级Java程序员的技术进阶之路

      据不完全统计,截至目前(2017.07)为止,中国Java程序员的数量已经超过了100万.而且,随着IT培训业的持续发展和大量的应届毕业生进入社会,Java程序员面临的竞争压力越来越大.那么,作为 ...

  6. JAVA - 深入JAVA 虚拟机 1

    Java虚拟机与程序的生命周期 Java虚拟机将结束生命周期 1.call System.exit(n) Terminates the currently running JVM. 2.程序正常执行结 ...

  7. Python爬虫从入门到放弃(十三)之 Scrapy框架的命令行详解

    这篇文章主要是对的scrapy命令行使用的一个介绍 创建爬虫项目 scrapy startproject 项目名例子如下: localhost:spider zhaofan$ scrapy start ...

  8. 增强for循环赋值

    增强for循环赋值 代码如下: double[] testList01 = new double[5]; java.util.Scanner sc = new java.util.Scanner(Sy ...

  9. 如何给Ionic写一个cordova插件

    写一个cordova插件 之前由javaWeb转html5开发,由于面临新技术,遂在适应的过程中极为挣扎,不过还好~,这个过程也极为短暂:现如今面临一些较为复杂的需求还会有一丝丝头痛,却没有一开始那么 ...

  10. 【学习笔记】C# 封装和继承

    封装 封装是实现面向对象程序设计的第一步 封装就是将数据.方法等集合在一个个单元中,我们称之为类 封装的意义在于保护代码/数据,屏蔽复杂性 继承 继承是所有面向对象语言不可缺少的部分 继承是为了实现类 ...