使用concurrent.futures和ProcessPoolExecutor来替代线程和进程
concurrent.futures和ProcessPoolExecutor这两个类实现的借口分别在不同的线程或进程中执行可调用的对象,这两个类在内部维护者一个工作线程或进程池,以及要执行的队列,这两个借口抽象的层级很高,无需关注实现细节
普通方法实现下载国旗
import os
import time
import sys import requests POP20_CC=('CN IN US ID BR PK NG BD RU JP'
'MX PH VN ET EG DE IR TR CD FR').split() BASE_URL='http://flupy.org/data/flags' DEST_DIR='downloads/' def save_flag(img,filename):
path=os.path.join(DEST_DIR,filename)
with open(path,'wb')as fp:
fp.write(img) def get_flag(cc):
url='{}/{cc}/{cc}.gif'.format(BASE_URL,cc=cc.lower())
resp=requests.get(url)
return resp.content def show(text):
print(text,end="")
sys.stdout.flush() def download_many(cc_list):
for cc in sorted(cc_list):
image=get_flag(cc)
show(cc)
save_flag(image,cc.lower()+'.gif') return len(cc_list) def main(download_many):
to=time.time()
count=download_many(POP20_CC)
elapsed=time.time()
msg='\n{} flags downloaded in {:.2f}s'
print(msg.format(count,elapsed)) if __name__=='__main__':
main(download_many)
替代多线程方法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from concurrent import futures
import sys
# sys.path.append(r"F:\regtest\asyncio!")
# from qw import save_flag,get_flag,show ,main
import os
import time
import sys MAX_WORKERS=20 import requests POP20_CC=('CN IN US ID BR PK NG BD RU JP'
'MX PH VN ET EG DE IR TR CD FR').split() BASE_URL='http://flupy.org/data/flags' DEST_DIR='downloads/'
def save_flag(img,filename):
path=os.path.join(DEST_DIR,filename)
with open(path,'wb')as fp:
fp.write(img) def get_flag(cc):
url='{}/{cc}/{cc}.gif'.format(BASE_URL,cc=cc.lower())
resp=requests.get(url)
return resp.content def show(text):
print(text,end="")
sys.stdout.flush() def download_one(cc):
image=get_flag(cc)
show(cc)
save_flag(image,cc.lower()+'.gif')
return cc def download_many(cc_list):
workers=min(MAX_WORKERS,len(cc_list))
with futures.ThreadPoolExecutor(workers) as executor:
res=executor.map(download_one,sorted(cc_list)) return len(list(res)) def main(download_many):
to=time.time()
count=download_many(POP20_CC)
elapsed=time.time()
msg='\n{} flags downloaded in {:.2f}s'
print(msg.format(count,elapsed)) if __name__=='__main__':
main(download_many)
有了这个神器就再也不用耗费精力去创建线程池或者进程池,以及队列来处理问题了。~
关于如何创建线程池进程池,在python基础篇~
使用concurrent.futures和ProcessPoolExecutor来替代线程和进程的更多相关文章
- concurrent.futures模块简单介绍(线程池,进程池)
一.基类Executor Executor类是ThreadPoolExecutor 和ProcessPoolExecutor 的基类.它为我们提供了如下方法: submit(fn, *args, ** ...
- 进程池和线程池 concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import time#线程池可以用shutdown submit from threading import current_thread from concurrent.futures impor ...
- 进程池与线程池(concurrent.futures)
from concurrent.futures import ProcessPoolExecutor import os,time,random def task(n): print('%s is r ...
- 基于concurrent.futures的进程池 和线程池
concurrent.futures:是关于进程池 和 线程池 的 官方文档 https://docs.python.org/dev/library/concurrent.futures.html 现 ...
- concurrent.futures模块(进程池/线程池)
需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...
- Python并发编程之线程池/进程池--concurrent.futures模块
一.关于concurrent.futures模块 Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/ ...
- (11)线程池(最新的concurrent.futures包去开启)
'''concurrent.futures是最新的开启线程池的包'''import timefrom concurrent.futures import ThreadPoolExecutor #开启线 ...
- concurrent.futures进线程池和协程
concurrent.futures 异步执行进程线程池的模块,一个抽象类,定义submit,map,shutdown方法 from concurrent.futures import Process ...
- python并发编程之进程池,线程池concurrent.futures
进程池与线程池 在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多, 这会对 ...
随机推荐
- 第一百八十五节,jQuery,Ajax 表单插件
jQuery,Ajax 表单插件 学习要点: 1.核心方法 2.option 参数 3.工具方法 传统的表单提交,需要多次跳转页面,极大的消耗资源也缺乏良好的用户体验.而这款 form.js 表单的 ...
- tcp/iP协议族——IP工作原理及实例具体解释(下)
IP协议具体解释 上一篇文章文章主要介绍了IP服务的特点,IPv4头部结构IP分片.并用tcpdump抓取数据包,来观察IP数据报传送过程中IP的格式,以及分片的过程.本文主要介绍IP路由,IP ...
- Servlet线程安全 Filter http://zwchen.iteye.com/blog/91088
概述 在探讨java线程安全前,让我们先简要介绍一下Java语言. 任何语言,如C++,C#,Java,它们都有相通之处,特别是语法,但如果有人问你,Java语言的核心是什么?类库?关键字?语法?似乎 ...
- 【spring boot logback】spring boot中logback日志乱码问题
在初次使用logback的自定义配置文件完整的控制spring boot日志后,发现了一个无法忍受的问题,就是日志乱码. 控制台看到打印日志乱码如下: 而日志文件打开: 记事本打开 sublime打开 ...
- 【BZOJ3620】似乎在梦中见过的样子 KMP
[BZOJ3620]似乎在梦中见过的样子 Description “Madoka,不要相信 QB!”伴随着 Homura 的失望地喊叫,Madoka 与 QB 签订了契约. 这是 Modoka 的一个 ...
- D - Find a way
D - Find a way Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Desc ...
- SpringMVC 资源国际化实现以及常见问题
资源国际化可以很方便的实现web项目语言的切换,解决了web项目按需显示不同语言界面的问题. SpringMVC 的资源国际化基于JDK的java.util.ResourceBundle实现,经过Sp ...
- C# Static修饰符的作用
MSDN上的定义 Use the static modifier to declare a static member, which belongs to the type itself rather ...
- C#通过反射打开相应窗体方法
C#单击菜单栏或工具栏时通过反射打开窗体的方法,可以以取代长长的if-else或switch-case语句.要点:将菜单或工具栏项的名称设置为与相应窗体名称相同(关键). private void M ...
- MySQL复制(一):复制的基本步骤
从这里开始,对复制的内容开始做一些详细的描述,复制从简单到入门 复制最简单的模式如下 基本的三个简单步骤 1 配置一个服务器为master 2 配置一个服务器为slave 3 将slave连接到mas ...