python线程池

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

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

该示例如下所示,通过线程池发送服务器请求

[En]

The example is as follows, sending a server request through a thread pool

服务端:

# 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()

运行结果:

服务端:

python线程池

客户端:

python线程池

Original: https://www.cnblogs.com/liyuanhong/p/15767817.html
Author: 远洪
Title: python线程池

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/7364/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部