Python标准模块--concurrent.futures(进程池,线程池)
python为我们提供的标准模块concurrent.futures里面有ThreadPoolExecutor(线程池)和ProcessPoolExecutor(进程池)两个模块. 在这个模块里他们俩在用法上是一样的.
concurrent.futures官方文档: https://docs.python.org/dev/library/concurrent.futures.html
#1 介绍
concurrent.futures模块提供了高度封装的异步调用接口
ThreadPoolExecutor:线程池,提供异步调用
ProcessPoolExecutor: 进程池,提供异步调用
Both implement the same interface, which is defined
by the abstract Executor class. #2 基本方法
#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)
回调函数
#介绍
The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned. class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None)
An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is lower or equal to 0, then a ValueError will be raised. # 用法示例
from concurrent.futures import ThreadPoolExecutor
import time def func(n):
time.sleep(1)
print(">>>", n)
return n*n if __name__ == '__main__':
t_pool = ThreadPoolExecutor(max_workers=5) # 线程池中最多不要超过cup个数*5
t_list = []
for i in range(20):
res = t_pool.submit(func, i)
t_list.append(res)
t_pool.shutdown() # 等待子线程结束, 再执行父进程 相当于相当于进程池的pool.close()+pool.join()操作
for resl in t_list:
print(resl.result()) # 结果是有序的, 这是因为t_list中的元素就是
# 有序的,所以循环迭代从结果对象中取出的值也是有序的
ThreadPoolExecutor
#介绍
ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously.
class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')
An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously. Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor. New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging. #用法
与ThreadPoolExecutor相同, 将ThreadPoolExecutor换成Process就可以了
ProcessPoolExecutor
from concurrent.futures import ThreadPoolExecutor
import time def func(n):
time.sleep(1)
print(">>>", n)
return n*n if __name__ == '__main__':
t_pool = ThreadPoolExecutor(max_workers=5)
res_g = t_pool.map(func,range(20))# 取代了for + submit 得到的结果是一个生成器对象
t_pool.shutdown()
print("主线程")
for ress in res_g:
print(ress)
map用法示例
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from multiprocessing import Pool
import requests
import json
import os def get_page(url):
print('<进程%s> get %s' %(os.getpid(),url))
respone=requests.get(url)
if respone.status_code == 200:
return {'url':url,'text':respone.text} def parse_page(res):
res=res.result()
print('<进程%s> parse %s' %(os.getpid(),res['url']))
parse_res='url:<%s> size:[%s]\n' %(res['url'],len(res['text']))
with open('db.txt','a') as f:
f.write(parse_res) if __name__ == '__main__':
urls=[
'https://www.baidu.com',
'https://www.python.org',
'https://www.openstack.org',
'https://help.github.com/',
'http://www.sina.com.cn/'
] # p=Pool(3)
# for url in urls:
# p.apply_async(get_page,args=(url,),callback=pasrse_page)
# p.close()
# p.join() p=ProcessPoolExecutor(3)
for url in urls:
p.submit(get_page,url).add_done_callback(parse_page) #parse_page拿到的是一个future对象obj,需要用obj.result()拿到结果
回调函数
Python标准模块--concurrent.futures(进程池,线程池)的更多相关文章
- Python标准模块--concurrent.futures 进程池线程池终极用法
		
concurrent.futures 这个模块是异步调用的机制concurrent.futures 提交任务都是用submitfor + submit 多个任务的提交shutdown 是等效于Pool ...
 - Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures
		
参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...
 - python 全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)
		
昨日内容回顾 线程什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的 一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的在当 ...
 - python全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)
		
昨日内容回顾 线程 什么是线程? 线程是cpu调度的最小单位 进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的 ...
 - Python标准模块--concurrent.futures
		
1 模块简介 concurrent.futures模块是在Python3.2中添加的.根据Python的官方文档,concurrent.futures模块提供给开发者一个执行异步调用的高级接口.con ...
 - Python--day41--线程池--python标准模块concurrent.futures
		
1,线程池代码示例:(注:进程池的话只要将以下代码中的ThreadPoolExecutor替换成ProcessPoolExecutor即可,这里不演示) import time from concur ...
 - concurrent.futures模块(进程池/线程池)
		
需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...
 - concurrent.futures模块(进程池&线程池)
		
1.线程池的概念 由于python中的GIL导致每个进程一次只能运行一个线程,在I/O密集型的操作中可以开启多线程,但是在使用多线程处理任务时候,不是线程越多越好,因为在线程切换的时候,需要切换上下文 ...
 - Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就绪,挂起,运行) ,***协程概念,yield模拟并发(有缺陷),Greenlet模块(手动切换),Gevent(协程并发)
		
Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就 ...
 
随机推荐
- 【转载】python抓取网页时候,判断网页编码格式
			
在web开发的时候我们经常会遇到网页抓取和分析,各种语言都可以完成这个功能.我喜欢用python实现,因为python提供了很多成熟的模块,可以很方便的实现网页抓取.但是在抓取过程中会遇到编码的问题, ...
 - python全栈开发   *   08知识点汇总   *    180608
			
08知识点梳理 文件操作一 .文件操作 r (只读)1.r (读) rb(字节)f=open("果蔬大杂烩",mode="r",encoding="U ...
 - ZOJ 4062 - Plants vs. Zombies - [二分+贪心][2018 ACM-ICPC Asia Qingdao Regional Problem E]
			
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=4062 题意: 现在在一条 $x$ 轴上玩植物大战僵尸,有 $n$ ...
 - linux命令:压缩解压打包工具大集合
			
目录 (1)zip 压缩.解压缩及归档工具有很多,今天小编就整理几个大家较为常用的. compress gzip bzip2 xz zip tar cpio 一.压缩.解压工具 用法 压缩 工具 压 ...
 - [本体论][UML][统一建模语言][软件建模][OWL]从本体论到UML到OWL
			
以下内容,是关于软件建模的方法与思路. UML与OWL都是基于本体论的建模语言. 本体论(哲学) 本体论(信息科学) UML(统一建模语言) more info 参考:[设计语言][统一建模语言][软 ...
 - 目标检测(六)YOLOv2__YOLO9000: Better, Faster, Stronger
			
项目链接 Abstract 在该论文中,作者首先介绍了对YOLOv1检测系统的各种改进措施.改进后得到的模型被称为YOLOv2,它使用了一种新颖的多尺度训练方法,使得模型可以在不同尺寸的输入上运行,并 ...
 - com.mysql.jdbc.Driver 与 org.gjt.mm.mysql.Driver的区别
			
com.mysql.jdbc.Driver的前身是org.gjt.mm.mysql.Driver,现在主要用com.mysql.jdbc.Driver,但为了保持兼容性保留了org.gjt.mm.my ...
 - CS1704问题汇总
			
“/”应用程序中的服务器错误. 编译错误 说明: 在编译向该请求提供服务所需资源的过程中出现错误.请检查下列特定错误详细信息并适当地修改源代码. 编译器错误消息: CS1704: 已经导入了具有相同的 ...
 - Jenkins+Jmeter持续集成笔记(一:环境准备)
			
整体思路: 通过Jmeter图形界面编写api测试脚本 ant 批量执行Jmeter脚本文件 将其集成到jenkins,设置执行频率与发送测试报告 运行环境 系统 配置 IP Centos7.1 1核 ...
 - MongoDB   "$" 字符 下标位置
			
我们可以修改列表里面元素的名字 例如: 修改age=34的数据,hobby里面的"足球"改为"网球" }) { "_id" : Object ...