使用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
进程池与线程池 在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多, 这会对 ...
随机推荐
- redhat ent 6.5 virtualbox虚拟机通过桥接方式配置主机-虚拟机的局域网
感谢: http://www.linuxidc.com/Linux/2012-06/62544.htm http://www.2cto.com/os/201204/126178.html Virual ...
- asp.net mvc FormsAuthentication一些问题
form验证最简单的一句 FormsAuthentication.SetAuthCookie(”userName", false); web.config里加上 <machine ...
- WPF-数据转换
有时我们展现的数据,需要进行转换,比如如果一个学生的成绩过了60,我们显示一个Pass的图片. XAML: <Window x:Class="DeepXAML.MainWindow&q ...
- 关于dll的pdb文件的小贴士
.pdb文件最好与生成它的.dll文件放在一起,这样调试的时候才有可能跟踪进dll的内部函数里.
- TP系统常量信息
[系统常量信息] 获取系统常量信息: 如果加参数true,会分组显示: 显示如下: [跨控制器调用] 一个控制器在执行的时候,可以实例化另外一个控制,并通过对象访问其指定方法. 跨控制器调用可以节省我 ...
- [转]libevent 环境配置
libevent 据说是IO复用的好东西.所以今天来耍耍. 1. 从官网下载源代码:http://libevent.org/,最新的版本已达到2.0. 2. 先把ubuntu系统自带的libevent ...
- [CTSC1999][网络流24题] 星际转移
36. [CTSC1999][网络流24题] 星际转移 ★★★☆ 输入文件:home.in 输出文件:home.out 简单对比时间限制:1 s 内存限制:128 MB «问题描述: ...
- Consul文档收藏
英文:https://www.consul.io/intro/getting-started/install.html 中文:http://www.liangxiansen.cn/2017/04/06 ...
- Anker—工作学习笔记
1.前言 最近在项目中用nginx做反向代理,需要动态生成nginx的配置.大概流程是用户在页面上新增域名.http或https协议以及端口信息,后台会根据域名自动生成一个nginx的server配置 ...
- 关于:before :after
首先要明白一种思想:结构和样式分离. 结构和样式分离,就意味着:没有样式表,HTML文档也是一个完整的文档:没有样式表,也能正常阅读用HTML表达的所有内容.明白这种思想就能很好理解样式表中使用--- ...