一 : 概述

  concurrent.futures模块提供了高度封装的异步调用接口

  ThreadPoolExecutor:线程池,提供异步调用

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

  两者都实现相同的接口,该接口由抽象执行器类定义。

二 : 基本方法

  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) 添加回调函数

 1 #介绍
2 ProcessPoolExecutor类是一个Executor子类,它使用进程池异步执行调用。ProcessPoolExecutor使用多处理模块,这允许它绕过全局解释器锁,但也意味着只能执行和返回可拾取的对象。
3
4 class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None)
5 一个Executor子类,使用最多包含max_workers进程的池异步执行调用。如果max_workers没有或没有给定,它将默认为机器上的处理器数量。如果max_workers小于或等于0,则会引发ValueError。 6
7
8 #用法
9 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
10
11 import os,time,random
12 def task(n):
13 print('%s is runing' %os.getpid())
14 time.sleep(random.randint(1,3))
15 return n**2
16
17 if __name__ == '__main__':
18
19 executor=ProcessPoolExecutor(max_workers=3)
20
21 futures=[]
22 for i in range(11):
23 future=executor.submit(task,i)
24 futures.append(future)
25 executor.shutdown(True)
26 print('+++>')
27 for future in futures:
28 print(future.result())
29
30 ProcessPoolExecutor
#介绍
ThreadPoolExecutor是一个Executor子类,它使用线程池异步执行调用。
class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')
一个Executor子类,它使用最多包含max_workers线程的池异步执行调用。 在3.5版中发生了更改:如果没有或没有指定max_workers,它将默认为机器上的处理器数量乘以5,假设ThreadPoolExecutor经常用于重叠I/O而不是CPU工作,并且Worker的数量应该高于ProcessPoolExecutor的工作人员数量。版本3.6中的新增功能:添加了thread_name_prefix参数,以允许用户控制线程。由池创建的工作线程的线程名称,以便于调试。 #用法
与ProcessPoolExecutor相同 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的用法
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()拿到结果 回调函数

转载至:https://www.cnblogs.com/DoingBe/p/9545066.html

PYTHON中的CONCURRENT.FUTURES模块的更多相关文章

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

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

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

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

  3. Python之线程 3 - 信号量、事件、线程队列与concurrent.futures模块

    一 信号量 二 事件 三 条件Condition 四 定时器(了解) 五 线程队列 六 标准模块-concurrent.futures 基本方法 ThreadPoolExecutor的简单使用 Pro ...

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

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

  5. 《转载》Python并发编程之线程池/进程池--concurrent.futures模块

    本文转载自Python并发编程之线程池/进程池--concurrent.futures模块 一.关于concurrent.futures模块 Python标准库为我们提供了threading和mult ...

  6. Python之路(第四十六篇)多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)

    一.线程池 很久(python2.6)之前python没有官方的线程池模块,只有第三方的threadpool模块, 之后再python2.6加入了multiprocessing.dummy 作为可以使 ...

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

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

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

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

  9. python之concurrent.futures模块

    一.concurrent.futures模块简介 concurrent.futures 模块提供了并发执行调用的高级接口 并发可以使用threads执行,使用ThreadPoolExecutor 或 ...

  10. Python之concurrent.futures模块的使用

    concurrent.futures的作用:       管理并发任务池.concurrent.futures模块提供了使用工作线程或进程池运行任务的接口.线程和进程池API都是一样,所以应用只做最小 ...

随机推荐

  1. 元数据库 information_schema.tables

    转  https://www.cnblogs.com/ssslinppp/p/6178636.html 1.information_schema数据库 对于mysql和Infobright等数据库,i ...

  2. 【ccc】为了ds的ccc2

    作业: #include <stdio.h> #include<string.h> int main(){ char s[100]; gets(s); int len; len ...

  3. 使用xamarin开发Android、iOS报错failed to open directory: 系统找不到指定的文件

    使用vs2019学习xamarin时,创建新程序.使用模拟器真机等测试都报错如下图错误: 调整AndroidManifest.xml和设备调试属性,打开[Android SDK和工具]安装可能需要的S ...

  4. STM32F4库函数初始化系列:DMA串口接收

    1 void _UART2_Configuration(void) 2 { 3 USART_InitTypeDef USART_InitStructure; 4 5 USART_OverSamplin ...

  5. 【TS】基础类型

    在ts中定义基础类型, 语法 : let 变量名 : 数据类型 = 值 // 布尔类型 ----boolean let flag : boolean = true flag = false 在赋值的时 ...

  6. centos7设置python路径

    直接在命令行运行.py 文件: [clouder@ana53 common]$ python3 driver.py Traceback (most recent call last): File &q ...

  7. 基于jib-maven-plugin快速构建微服务docker镜像

    一.说明 本文介绍基于 Maven 插件 jib-maven-plugin 实现快速构建 Spring Boot 程序镜像,并推送到远程仓库中,且 无需安装 Docker 环境 . Jib 是 Goo ...

  8. php使用PDO获取结果集的方法

    php使用PDO获取结果集的方法  转载:https://www.jb51.net/article/105797.htm 更新时间:2017年02月16日 11:11:42   作者:水晶依恋     ...

  9. LAMP环境搭建——最详细的手工编译

    环境:阿里云服务器ECS,Alibaba Cloud Linux 3.2104 LTS 64位 ,2核(vCPU) 2 GiB LAMP 是搭建Web应用时最常用的环境,LAMP 分别表示 Linux ...

  10. 使用Shapefile C Library读取shp文件并使用OpenGL绘制

    1. 概述 坐标数据是空间数据文件的核心,空间数据的数据量往往是很大的.数据可视化是GIS的一个核心应用,绘制海量的坐标数据始终是一个考验设备性能的难题,使用GPU进行绘制可有效减少CPU的负载,提升 ...