concurrent:并发

  Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码。从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutorProcessPoolExecutor两个类,实现了对threadingmultiprocessing的更高级的抽象,对编写线程池/进程池提供了直接的支持。 
concurrent.futures基础模块是executor和future。

  Executor  

  Executor是一个抽象类,它不能被直接使用。它为具体的异步执行定义了一些基本的方法。 ThreadPoolExecutor和ProcessPoolExecutor继承了Executor,分别被用来创建线程池和进程池的代码。

  submit方法

  Executor中定义了submit()方法,这个方法的作用是提交一个可执行的回调task,并返回一个future实例。future对象代表的就是给定的调用。

  我们使用submit方法来往线程池中加入一个task,submit返回一个Future对象,对于Future对象可以简单地理解为一个在未来完成的操作。

  map方法

  Exectuor还为我们提供了map方法,和内建的map用法类似。映射。

  future

  Future实例是由Executor.submit()创建的。可以理解为一个在未来完成的操作,这是异步编程的基础。通常情况下,我们执行io操作,访问url时(如下)在等待结果返回之前会产生阻塞,cpu不能做其他事情,而Future的引入帮助我们在等待的这段时间可以完成其他的操作。

  示例:

  

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os,time,random
def foo(i):
print('%s is running %s'%(os.getpid(),i))
time.sleep(random.randint(1, 3))
return i**2
if __name__ == '__main__':
print('cpu_num:',os.cpu_count())
executor=ProcessPoolExecutor()
print('executor',executor,type(executor))
# futures=[]
# for i in range(10):
# future=executor.submit(foo,i)
# futures.append(future)
futures=[executor.submit(foo,i) for i in range(10)]
executor.shutdown()
#程序运行到这里有明显的时间间隔,可见是在shutdown存在的情况下,程序将future全部执行完,才继续往下走的
print('主')
print(futures)
for future in futures:
print(future.result())

  输出:

cpu_num: 8
executor <concurrent.futures.process.ProcessPoolExecutor object at 0x00000276745AA978> <class 'concurrent.futures.process.ProcessPoolExecutor'>
11740 is running 0
3156 is running 1
9928 is running 2
2208 is running 3
2324 is running 4
13080 is running 5
1892 is running 6
2964 is running 7
2208 is running 8
2324 is running 9

[<Future at 0x27674900e10 state=finished returned int>, <Future at 0x27674949dd8 state=finished returned int>, <Future at 0x27674949e80 state=finished returned int>, <Future at 0x27674949f28 state=finished returned int>, <Future at 0x27674949fd0 state=finished returned int>, <Future at 0x2767495a0b8 state=finished returned int>, <Future at 0x2767495a198 state=finished returned int>, <Future at 0x2767495a278 state=finished returned int>, <Future at 0x2767495a358 state=finished returned int>, <Future at 0x2767495a438 state=finished returned int>]
0
1
4
9
16
25
36
49
64
81

  

  利用ThreadProcessExecutor爬虫

  

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import requests
def get(url):
r=requests.get(url)
return {'url':url,'text':r.text}
def parse(future):
dic=future.result() #future对象调用result方法取其值、
f=open('db.text','a')
date='url:%s\n'%len(dic['text'])
f.write(date)
f.close()
if __name__ == '__main__':
executor=ThreadPoolExecutor()
url_l = ['http://cn.bing.com/', 'http://www.cnblogs.com/wupeiqi/', 'http://www.cnblogs.com/654321cc/',
'https://www.cnblogs.com/', 'http://society.people.com.cn/n1/2017/1012/c1008-29581930.html',
'http://www.xilu.com/news/shaonianxinzangyou5gedong.html', ]
futures=[]
for url in url_l:
executor.submit(get,url).add_done_callback(parse) #与Pool进程池回调函数接收的是A函数的返回值(对象ApplyResult.get()得到的值)。
executor.shutdown() #这里回调函数parse,接收的参数是submit生成的 Future对象。
print('主')

  输出:

  

python并发之concurrent.futures的更多相关文章

  1. Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures

    参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...

  2. python 全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)

    昨日内容回顾 线程什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的 一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的在当 ...

  3. python全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)

    昨日内容回顾 线程 什么是线程? 线程是cpu调度的最小单位 进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的 ...

  4. Python标准模块--concurrent.futures

    1 模块简介 concurrent.futures模块是在Python3.2中添加的.根据Python的官方文档,concurrent.futures模块提供给开发者一个执行异步调用的高级接口.con ...

  5. 在python中使用concurrent.futures实现进程池和线程池

    #!/usr/bin/env python # -*- coding: utf-8 -*- import concurrent.futures import time number_list = [1 ...

  6. Python标准模块--concurrent.futures(进程池,线程池)

    python为我们提供的标准模块concurrent.futures里面有ThreadPoolExecutor(线程池)和ProcessPoolExecutor(进程池)两个模块. 在这个模块里他们俩 ...

  7. Python标准模块--concurrent.futures 进程池线程池终极用法

    concurrent.futures 这个模块是异步调用的机制concurrent.futures 提交任务都是用submitfor + submit 多个任务的提交shutdown 是等效于Pool ...

  8. Python--day41--线程池--python标准模块concurrent.futures

    1,线程池代码示例:(注:进程池的话只要将以下代码中的ThreadPoolExecutor替换成ProcessPoolExecutor即可,这里不演示) import time from concur ...

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

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

随机推荐

  1. python_95_类变量的作用及析构函数

    参考:http://www.cnblogs.com/alex3714/articles/5188179.html #类变量的用途:大家共有的属性,节省内存 class Person(): cn='Ch ...

  2. Python基础篇 -- 集合

    set集合 set 中的元素是不重复的,无序的 里面的元素必须是可hash的,(int str tuple bool) set 就是dict 类型的数据,但是不保存value 只保存 key set集 ...

  3. 03_2_JAVA中的面向对象与内存解析

    03_2_JAVA中的面向对象与内存解析 1. 成员变量 成员变量可以是Java语言中任何一种数据类型(包括基本数据类型和引用数据类型) 在定义成员变量时可以对其初始化,如果不对其初始化,Java使用 ...

  4. c++ 调用php

    int _System(const char * cmd, std::string& strRet) { FILE * fp; char * p = NULL; ; if ((fp = _po ...

  5. 新环境安装 python3

    参考 安装 python3 时,不要覆盖原环境的 python2.因为环境中有些程序是依赖 2 的,比如 yum.直接覆盖是会影响环境的. 最好的是编译安装 python3,执行指令是用 python ...

  6. node 文件下载到本地 (支持中文文件名)

    downloadfile:function(req,res,next){ var name= encodeURI(req.query.name); var path= req.query.url; v ...

  7. 【php】命名空间的影响

    命名空间对代码的影响 类(包含抽象类和traits) 接口 常量 函数 ​

  8. python爬虫基础16-cookie在爬虫中的应用

    Cookie的Python爬虫应用 Cookie是什么 Cookie,有时也用其复数形式 Cookies,英文是饼干的意思.指某些网站为了辨别用户身份.进行 session 跟踪而储存在用户本地终端上 ...

  9. Python json和simplejson的使用

    在Python中,json数据和字符串的转换可以使用json模块或simplejson模块. json从Python2.6开始内置到了Python标准库中,我们不需要安装即可直接使用. simplej ...

  10. MongoDB之Replica Sets环境搭建

    最近学习MongoDB,这两天在搭建复制集的时候碰到了不少问题,也踩了好多坑,现在在这里记录下来,以供自己和他人参考 (因为本人是初学者,所以遇到的问题也会比较初级,所以本文也比较适合初学者查阅) 背 ...