python线程池


一、废弃的第三方线程池库 :threadpool

threadpool已经不建议使用了,官方文档推荐我们使用标准库中的 multiprocessing 或者  asyncio.A 来替代

官网地址:https://pypi.org/project/threadpool/

 

 

二、python 3.2之后,标准昆中为我们提供了,ThreadPoolExecutor线程池

案例如下,通过线程池来发送服务端请求

服务端:

# coding: utf-8
from flask import Flask
import time
import random

app = Flask(__name__)

reqCount = 0

@app.route("/")
def hello_world():
    global reqCount
    reqCount = reqCount + 1
    curCount = reqCount
    randTime = random.randint(0,3)
    time.sleep(randTime)
    print(reqCount,randTime)
    return "this is the " + str(curCount) + " request"
    
if __name__ == "__main__":
    app.run(host="0.0.0.0",port=8000,debug=True)

客户端:

# coding: utf-8
import requests
import time
from concurrent.futures import ThreadPoolExecutor

def reqlocal():
    r = requests.get('http://localhost:8000')
    rTxt = r.text
    print(rTxt)

def threadPoolTest():
    startTime = int(time.time())
    loopCnt = 30
    with ThreadPoolExecutor(max_workers=10) as t:
        for i in range(loopCnt):
            task = t.submit(reqlocal)
            task.done()
    entdTime = int(time.time())
    proTime = entdTime - startTime
    print("总耗时:",proTime)
    
if __name__ == "__main__":
    threadPoolTest()

运行结果:

服务端:

 

 客户端:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM