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来替代线程和进程的更多相关文章

  1. concurrent.futures模块简单介绍(线程池,进程池)

    一.基类Executor Executor类是ThreadPoolExecutor 和ProcessPoolExecutor 的基类.它为我们提供了如下方法: submit(fn, *args, ** ...

  2. 进程池和线程池 concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor

    import time#线程池可以用shutdown submit from threading import current_thread from concurrent.futures impor ...

  3. 进程池与线程池(concurrent.futures)

    from concurrent.futures import ProcessPoolExecutor import os,time,random def task(n): print('%s is r ...

  4. 基于concurrent.futures的进程池 和线程池

    concurrent.futures:是关于进程池 和 线程池 的 官方文档 https://docs.python.org/dev/library/concurrent.futures.html 现 ...

  5. concurrent.futures模块(进程池/线程池)

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

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

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

  7. (11)线程池(最新的concurrent.futures包去开启)

    '''concurrent.futures是最新的开启线程池的包'''import timefrom concurrent.futures import ThreadPoolExecutor #开启线 ...

  8. concurrent.futures进线程池和协程

    concurrent.futures 异步执行进程线程池的模块,一个抽象类,定义submit,map,shutdown方法 from concurrent.futures import Process ...

  9. python并发编程之进程池,线程池concurrent.futures

    进程池与线程池 在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多, 这会对 ...

随机推荐

  1. 补装老版本的Java SE

    到oracle注册账号下载bin文件 在bin文件下载目录打开终端复制下面到命令 # chmod +x jdk-6u21-linux-i586.bin 注意版本不同,比如我这次下载到是6u45 chm ...

  2. OpenCV学习笔记十四:opencv_objdetect模块

    一,简介: 该库用于目标检测.

  3. Linux 下 -bash: mysql: command not found解决办法

    -bash: mysql: command not found 1.vim ~/.bash_profile 最下面写 export PATH=$PATH:/usr/local/mysql/bin(你的 ...

  4. linux下装locustio

    升级Python版本 #python centOS6.8中默认安装的是2.6版本,因为我在安装到后面的时候报错Python版本较低,所以可以先把python版本升级到2.7: 直接在命令行输入:#wg ...

  5. 基于ormlite创建数据库存储数据案例

    一直不知道安卓创建数据库存储数据,以前遇到过,但是没有深入研究,今天仔细的看了一下,学习到了一点知识 直接看代码了 public class DatabaseHelper extends OrmLit ...

  6. hdu1174(3维射线与圆是否相交)

    简单的题意,要注意z2 = h2*0.9-r2 #include <iostream> #include <cmath> #include <vector> #in ...

  7. ASP-Server.Transfer-Response.Redirect

    Server.Transfer Transfer 方法把一个 ASP 文件中创建的所有状态信息(所有 application/session 变量以及所有 request 集合中的项目)发送(传输)到 ...

  8. 【转】NAS、DAS和SAN存储的特点及主要区别

    接触过存储设备的朋友应该对NAS.DAS和SAN存储不陌生,作为目前三种常见的存储方式,被广泛应用于企业存储设备中,那么NAS.DAS和SAN这三种存储分别有什么特点,又有何区别呢? 一.NAS存储特 ...

  9. python函数的学习笔记

    这篇文章是我关于学习python函数的一些总结 一.随着函数的引入,这里首先要说的就是全局变量和局部变量了. 什么是全局变量.什么是局部变量: 全局变量就是全局都能调用的变量,一般都在文件的开头,顶头 ...

  10. Nuxt使用element-ui

    废话不多说,在Nuxt中引入Nuxt其实很简单,分下面几步 一.安装element-ui依赖 打开nuxt项目以后,在Terminal中通过 npm i element-ui -S 即可安装eleme ...