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. shell学习五十八天----/proc文件系统

    /proc文件系统 前言:linux中的/proc文件系统,由一组文件夹和文件组成,挂载(mount)与/proc文件夹下. /proc文件系统是一种虚拟文件系统,以文件系统文件夹和文件形式,提供一个 ...

  2. Servlet线程安全 Filter http://zwchen.iteye.com/blog/91088

    概述 在探讨java线程安全前,让我们先简要介绍一下Java语言. 任何语言,如C++,C#,Java,它们都有相通之处,特别是语法,但如果有人问你,Java语言的核心是什么?类库?关键字?语法?似乎 ...

  3. 一些常用的html css整理--文本长度截取

    div+css设置列表div超出部分显示...(单行文本) width:200px; //指定宽度: overflow:hidden; //将超出内容隐藏 text-overflow:ellipsis ...

  4. Codeforces 460 D. Little Victor and Set

    暴力+构造 If r - l ≤ 4 we can all subsets of size not greater than k. Else, if k = 1, obviously that ans ...

  5. 记录-java执行请求的URL

    package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStr ...

  6. 使用 Docker 部署 MongoDB 分片

    创建配置服务复制集 docker run --name configsvr0 -d mongo:3.6.2-jessie --configsvr --replSet "rs_configsv ...

  7. iOS反射:把对象直接转化成NSDictionary

    在IOS的网络编程中,通常我们需要将一些实体数据保存到NSDictionary,在获得NSDictionary后即可直接使用iOS 5后的NSJSONSerialization类型的dataWithJ ...

  8. 小程序html 显示 图片处理

    let arr = [] for (const v of r.data.data ){ // v.content = v.content.replace(/<img/g ,' <image ...

  9. 三、Nuxt项目目录结构

    使用IDE打开我们初始化完的新项目,然后发现目录如下图所示 现在来介绍一下每个目录和文件 .idea           是我使用的IDE是IDEA自动生成的,跟项目无关 .nuxt          ...

  10. Impala SQL 语言元素(翻译)

    摘要: http://www.cloudera.com/content/cloudera-content/cloudera-docs/Impala/latest/Installing-and-Usin ...