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. Spring入门之通过注解 处理 数据库事务

    用Spring 中的事务写的银行转帐的例子:(环境同上一个贴子) 一.表结构: (create table (id int,username varchar(10),salary int);) 二.文 ...

  2. java字符编码详解

    引用自:http://blog.csdn.net/jerry_bj/article/details/5714745 GBK.GB2312.iso-8859-1之间的区别 GB2312,由中华人民共和国 ...

  3. hdu 1816(二分+2-sat)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1816 思路:首先将每把钥匙i拆成两个点i和i+2n,分别表示选与不选,对于被分成n对的钥匙,由于只能选 ...

  4. Unity3d 游戏退出界面1

    功能需求:点击退出按钮,弹出“退出”UI,询问玩家是否退出游戏: 退出按钮 退出UI: publicclass GameQuit : MonoBehaviour { // 取消按钮 public  G ...

  5. 事务处理笔记《一》ADO.NET级别的事务

    现在我们对事务的概念和原理都有所了解了,并且作为已经有一些基础的C#开发者,我们已经熟知编写数据库交互程序的一些要点,即: (1)使用SqlConnection类的对象的Open()方法建立与数据库服 ...

  6. spoj 10628

    http://www.spoj.com/problems/COT/ 树上第k小元素 LCA + 可持久化线段树 每个新的版本都是由其父亲版本转化而来. #include <cstdio> ...

  7. poj2420(模拟退火大法好)

    // // main.cpp // poj2420 // // Created by 陈加寿 on 16/2/13. // Copyright © 2016年 chenhuan001. All rig ...

  8. (转)gethostbyname() -- 用域名或主机名获取IP地址

    struct hostent *gethostbyname(const char *name); 这个函数的传入值是域名或者主机名,例如"www.google.cn"等等.传出值, ...

  9. codevs1044 拦截导弹==洛谷 P1020 导弹拦截

    P1020 导弹拦截 题目描述 某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统.但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度.某天 ...

  10. 【python】-- Django ORM(进阶)

    Django ORM(进阶) 上一篇博文简述了Django ORM的单表操作,在本篇博文中主要简述Django ORM的连表操作. 一.一对多:models.ForeignKey() 应用场景:当一张 ...