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

    运行结果:

    服务端:

     客户端:

    博客里大都是转载的内容,其目的主要用户知识的组织和管理。
  • 相关阅读:
    Hibernate工作原理
    Java jar包查询下载方法
    http状态码(HTTP Status Code)
    Android Broadcast Receiver (广播接收者)
    Android ViewPager组件
    Android Activity属性
    Android XML Drawable
    Android 样式布局
    Android Activity的LaunchMode四种模式
    Android Layout布局
  • 原文地址:https://www.cnblogs.com/liyuanhong/p/15767817.html
Copyright © 2020-2023  润新知