python中的进程池和线程池,,Python标准模块
python中的进程池和线程池,,Python标准模块
Python标准模块-concurrent.futures
#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)回调函数
使用方法示例
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutorimport requests# 给线程池设置最大工作的线程数pool = ThreadPoolExecutor(10)urls = [ ‘http://cms-bucket.nosdn.127.net/2018/10/16/10e36050547445f6b8972daf7373a22‘ ‘2.jpeg‘, ‘http://kwcdn.000dn.com/swfs/59/39972xmyj0206/pm.jpg‘, ‘http://pic-bucket.nosdn.127.net/photo/0008/2018-10-14/DU48KHUS2FKJ0008NOS‘ ‘.jpg‘, ‘http://cms-bucket.nosdn.127.net/2018/10/16/b3a3fab2d65a41b79e0764727ae6d17‘ ‘9.jpeg‘, ‘http://cms-bucket.nosdn.127.net/2018/10/15/92cbe61fc5ec40ab94f5d2f0ed86771‘ ‘8.jpeg‘,]def task(url): response = requests.get(url) return response# response会传递到call_back的参数中def call_back(response): # 拿到的是一个future的对象 # 从对象中取出task中返回的结果 response.result() # 对回调过来的信息进行解析 passfor url in urls: # 使用回调函数能够用返回的结果实时的去解析, 实现异步非阻塞 pool.submit(task, url).add_done_callback(call_back)# 如果使用shutdown会等待所有任务执行结束后再去执行主线程中的代码# pool.shutdown(True)
python中的进程池和线程池
相关内容
- 使用cython库对python代码进行动态编译达到加速效果,
- python: 多态与虚函数;,,通过python的a
- python:for循环,,for循环可以遍历任
- python serial模块使用,是pyserial而非serial,,1 import s
- python将dict中的unicode打印成中文,,python将dic
- python 获取网站IP以及服务器,,写了一个识别网站的i
- 【python-leetcode904-滑动窗口法】水果成篮,,问题描述:
- Python rsplit() 方法,,描述Python r
- python字符串,赋值和is的区别,,1. == 与 is
- python 3.5.2 install pillow,,1. 首先尝试从官网
评论关闭