使用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
进程池与线程池 在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多, 这会对 ...
随机推荐
- ini文件
*.INI内容 [NETWORK] ServerIP=100.100.100.53 程序: main() { char ip[16]; DWORD num=0; num=GetPrivateProfi ...
- il code swtich
public enum RangeItemType { CompanyPicker = 1, //公司STR_COMPANY BrDivPicker = 2, //分行STR_BRDIV Depart ...
- C++11写算法之插入排序
插入排序,是指将从1 –> size-1的数一个个插入到前面已经排序好的数组中. 时间复杂度:O(n^2) , O(nlgn) (lgn指使用二分查找插入点位置) 空间复杂度:O(1) // ...
- 加号选择器(ul>li + li)
<head> <meta charset="UTF-8"> <title>+ selector</title> <style& ...
- Android无线测试之—UiAutomator UiSelector API介绍之二
Android的布局与组件及组件属性介绍 一.布局: 1)线性布局:控价在线性方向上一次排列 2)表格布局:向表格一样有标准的行和列 3)相对布局:通过相对定位的方式让控件出现在布局的任何位置 4)帧 ...
- selenium的元素定位-鼠标事件
鼠标事件 ActionChains 类提供了鼠标操作的常用方法: perform(): 执行所有 ActionChains 中存储的行为: context_click(): 右击: double_cl ...
- IntelliJ IDEA使用手册
开发工具现在转到IDEA了,看到关于该工具很好的入门文档,于是记录一下: IntelliJ IDEA 使用教程
- hihoCoder 1549 或运算和
#1549 : 或运算和 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定N个数A1...AN (0 <= Ai < 220) 和一个正整数K,我们用An ...
- idea 右下角不显示git分支
开发工程中遇到idea右下角不显示git分支问题: 解决方案:查找资料说是需要打开VCS->Enable version control. 但是Enable version control 已经 ...
- ssh常用
目录操作:rm -rf mydir /*删除mydir目录*/mkdir dirname /*创建名为dirname的目录*/cd mydir /*进入mydir目录*/cd – /*回上一级目录*/ ...