concurrent.futures模块提供了高度封装的异步调用接口,它内部有关的两个池

ThreadPoolExecutor:线程池,提供异步调用,其基础就是老版的Pool

ProcessPoolExecutor: 进程池,提供异步调用

方法

ProcessPoolExecutor(n):n表示池里面存放多少个进程,之后的连接最大就是n的值

submit(fn,*args,**kwargs)  异步提交任务

map(func, *iterables, timeout=None, chunksize=1) 取代for循环submit的操作

shutdown(wait=True) 相当于进程池的pool.close()+pool.join()操作
wait=True,等待池内所有任务执行完毕回收完资源后才继续,--------》默认
wait=False,立即返回,并不会等待池内的任务执行完毕
但不管wait参数为何值,整个程序都会等到所有任务执行完毕
submit和map必须在shutdown之前

result(timeout=None) #取得结果 add_done_callback(fn) #回调函数
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import time,random,os def task(n):
print('%s is running'% os.getpid())
time.sleep(random.randint(1,3))
return n**2
def handle(res):
res=res.result()
print("handle res %s"%res) if __name__ == '__main__':
# #同步调用
# pool=ProcessPoolExecutor(8)
#
# for i in range(13):
# pool.submit(task, i).result() #变成同步调用,串行了,等待结果
# # pool.shutdown(wait=True) #关门等待所有进程完成
# pool.shutdown(wait=False)#默认wait就等于True
# # pool.submit(task,3333) #shutdown后不能使用submit命令
#
# print('主') #异步调用
pool=ProcessPoolExecutor(8)
for i in range(13):
obj=pool.submit(task,i)
obj.add_done_callback(handle) #这里用到了回调函数
pool.shutdown(wait=True) #关门等待所有进程完成
print('主')

ProcessPoolExecutor

#提交任务的两种方式
#同步调用:提交完任务后,就在原地等待,等待任务结束,拿到任务的返回值,才能继续下一行代码,导致程序串行执行
#异步调用+回调机制:提交完任务后,不在原地等待,任务一旦执行完毕就会触发回调函数的执行,程序是并发执行 #同步有可能是计算任务而在等待
#ProcessPoolExcutor基于pool开发的 #进程的执行状态
#阻塞:遇到i/o进入的一种状态,等待
#非阻塞:

进程其他说明

from concurrent.futures import ThreadPoolExecutor
from urllib import request
from threading import current_thread
import time def get(url):
print('%s get %s'%(current_thread().getName(),url))
response=request.urlopen(url)
time.sleep(2)
# print(response.read().decode('utf-8'))
return{'url':url,'content':response.read().decode('utf-8')} def parse(res):
res=res.result()
print('parse:[%s] res:[%s]'%(res['url'],len(res['content']))) # get('http://www.baidu.com')
if __name__ == '__main__':
pool=ThreadPoolExecutor(2) urls=[
'https://www.baidu.com',
'https://www.python.org',
'https://www.openstack.org',
'https://www.openstack.org',
'https://www.openstack.org',
'https://www.openstack.org',
'https://www.openstack.org',
'https://www.openstack.org', ] for url in urls:
pool.submit(get,url).add_done_callback(parse)

ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

import os,time,random
def task(n):
print('%s is runing' %os.getpid())
time.sleep(random.randint(1,3))
return n**2 if __name__ == '__main__': executor=ThreadPoolExecutor(max_workers=3) # for i in range(11):
# future=executor.submit(task,i) executor.map(task,range(1,12)) #map取代了for+submit

map用法

回调 略

concurrent.futures模块 -----进程池 ---线程池 ---回调的更多相关文章

  1. 使用concurrent.futures模块中的线程池与进程池

    使用concurrent.futures模块中的线程池与进程池 线程池与进程池 以线程池举例,系统使用多线程方式运行时,会产生大量的线程创建与销毁,创建与销毁必定会带来一定的消耗,甚至导致系统资源的崩 ...

  2. concurrent.futures模块(进程池&线程池)

    1.线程池的概念 由于python中的GIL导致每个进程一次只能运行一个线程,在I/O密集型的操作中可以开启多线程,但是在使用多线程处理任务时候,不是线程越多越好,因为在线程切换的时候,需要切换上下文 ...

  3. concurrent.futures模块(进程池/线程池)

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

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

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

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

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

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

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

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

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

  8. 使用concurrent.futures模块并发,实现进程池、线程池

    Python标准库为我们提供了threading和multiprocessing模块编写相应的异步多线程/多进程代码 从Python3.2开始,标准库为我们提供了concurrent.futures模 ...

  9. 创建进程池与线程池concurrent.futures模块的使用

    一.进程池. 当并发的任务数量远远大于计算机所能承受的范围,即无法一次性开启过多的任务数量就应该考虑去 限制进程数或线程数,从而保证服务器不会因超载而瘫痪.这时候就出现了进程池和线程池. 二.conc ...

随机推荐

  1. Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(

    application.class要放在根目录下,否则会发生以下错误

  2. jsonp跨域设置cookie

    html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <tit ...

  3. JS获取坐标

    1.js获取对象的绝对坐标 方法1: function getAbsPoint(e) { var x = e.offsetLeft, y = e.offsetTop; while(e=e.offset ...

  4. SQL2000服务端配置-如何让外网访问SQL2000

    刚刚写了个DEMO,在内网来测试SQL2000后完全正常.现在想测试外网是否正常,毕竟路由器IP不固定,所以选择了路由器+花生壳免费域名(koma.5166.info),所以先安装花生壳客户端软件.下 ...

  5. webGL之three.js入门4--ThreeJS Editor入门篇

    因为工作需要,要看threejs editor的源码,顺便记录过程. github下载的源码目录是这样的 但是editor和其他文件夹内的内容的关联的,我需要将其独立出来并且编辑editor. 进入e ...

  6. Azure 认知服务 (3) 计算机视觉API - 分析图像,使用C#代码

    <Windows Azure Platform 系列文章目录> 在上一节中Azure 认知服务 (2) 计算机视觉API - 分析图像,笔者介绍了如何使用API测试控制台进行调试. 本章将 ...

  7. R语言数据挖掘相关包总结-转帖

    与数据挖掘有关或者有帮助的R包和函数的集合. 1.聚类 常用的包: fpc,cluster,pvclust,mclust 基于划分的方法: kmeans, pam, pamk, clara 基于层次的 ...

  8. js页面滚动时层智能浮动定位实现

    直接上代码 $.fn.smartFloat = function (className) { var position = function (element) { var top = element ...

  9. C++进阶--命名空间和关键字using

    //############################################################################ /* * C++关键字:using * * ...

  10. (转载)通向架构师的道路(第四天)之Tomcat性能调优-让小猫飞奔

    转载自:https://blog.csdn.net/lifetragedy/article/details/7708724 参考文章:tomcat以及常用web容器线程池的实现原理https://bl ...