使用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基础篇~

时间: 2025-01-17 09:26:51

使用concurrent.futures和ProcessPoolExecutor来替代线程和进程的相关文章

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

import time#线程池可以用shutdown submit from threading import current_thread from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor def f1(n): print(n) time.seelp(1) return n*n if __name__ =="__main__": tp = ThreadPoolExecutor(4) lst =

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

h2 { color: #fff; background-color: #f7af0d; padding: 3px; margin: 10px 0px } 一.关于concurrent.futures模块 Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要编写自己的线程池/进程池,以空间换时间.但从Python3.2开始,标准库为我们提供了conc

使用concurrent.futures模块并发,实现进程池、线程池

一.关于concurrent.futures模块 Python标准库为我们提供了threading和multiprocessing模块编写相应的异步多线程/多进程代码.从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类ThreadPoolExecutor和ProcessPoolExecutor继承了Executor,分别被用来创建线程池和进程池的代码.实现了对thread

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

进程池与线程池 在刚开始学多进程或多线程时,我们迫不及待地基于多进程或多线程实现并发的套接字通信,然而这种实现方式的致命缺陷是:服务的开启的进程数或线程数都会随着并发的客户端数目地增多而增多, 这会对服务端主机带来巨大的压力,甚至于不堪重负而瘫痪,于是我们必须对服务端开启的进程数或线程数加以控制,让机器在一个自己可以承受的范围内运行,这就是进程池或线程池的用途, 例如进程池,就是用来存放进程的池子,本质还是基于多进程,只不过是对开启进程的数目加上了限制 Python--concurrent.fu

创建进程池与线程池concurrent.futures模块的使用

一.进程池. 当并发的任务数量远远大于计算机所能承受的范围,即无法一次性开启过多的任务数量就应该考虑去 限制进程数或线程数,从而保证服务器不会因超载而瘫痪.这时候就出现了进程池和线程池. 二.concurrent.futures模块介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPoolExecutor:进程池,提供异步调用 Both implement the same interface,

35、concurrent.futures模块与协程

concurrent.futures  -Launching parallel tasks    concurrent.futures模块同时提供了进程池和线程池,它是将来的使用趋势,同样我们之前学习的进程池Pool和threadpool模块也可以使用. 对进程池疑惑的可以参阅:32进程池与回调函数http://www.cnblogs.com/liluning/p/7445457.html 对threadpool模块疑惑的可以看我闲暇时写的一段代码:(因为本人也不了解这个模块,代码里写的也是自己

concurrent.futures模块与协程

concurrent.futures  -Launching parallel tasks    concurrent.futures模块同时提供了进程池和线程池,它是将来的使用趋势,同样我们之前学习的进程池Pool和threadpool模块也可以使用. 对进程池疑惑的可以参阅:32进程池与回调函数http://www.cnblogs.com/liluning/p/7445457.html 对threadpool模块疑惑的可以看我闲暇时写的一段代码:(因为本人也不了解这个模块,代码里写的也是自己

python全栈开发基础【第二十六篇】(concurrent.futures模块、协程、Greenlet、Gevent)

注意 1.不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 2.只要你用并发,就会有锁的问题,但是你不能一直去自己加锁吧那么我们就用QUEUE,这样还解决了自动加锁的问题由Queue延伸出的一个点也非常重要的概念.以后写程序也会用到这个思想.就是生产者与消费者问题 一.Python标准模块--concurrent.futures(并发未来) concurent.future模块需要了解的 1.concurent

python并发之concurrent.futures

concurrent:并发 Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码.从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threading和multiprocessing的更高级的抽象,对编写线程池/进程池提供了直接的支持. concurrent.futures基础模块是executor和f