zoukankan      html  css  js  c++  java
  • python flask线程池用法

    flask线程池用法

    1.线程池的用法

    1. 在写任务调度的时候,难免遇到使用多线程、多进程、线程池、进程池的场景 ,
    from flask import Flask
    from time import sleep
    from concurrent.futures import ThreadPoolExecutor
    # DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
    executor = ThreadPoolExecutor(2)
    app = Flask(__name__)
    @app.route('/jobs')
    def run_jobs():
     # 通过submit函数提交执行的函数到线程池中,submit函数立即返回,不阻塞
     executor.submit(long_task, 'hello', 123)
     return 'long task running.'
    
    def long_task(arg1, arg2):
     print("args: %s %s!" % (arg1, arg2))
     sleep(5)
     print("Task is done!")
    
    if __name__ == '__main__':
     app.run()
    

    2.thread的用法

    import time
    from threading import Thread
    
    def async_fun(f):
    
        def inner_fun(*args, **kwargs):
    
            t = Thread(target=f, args=args, kwargs=kwargs)
    
            t.start()
    
        return inner_fun
    
    
    @async_fun
    
    def test_a():
    
        time.sleep(10)
    
        print("test a run")
    
    
    def test_b():
    
        test_a()
    
        print("test b run")
    
    test_b()
    

    3.flask开启多线程支持

    1)threaded : 多线程支持,默认为False,即不开启多线程;

    app.run(threaded=True)
    

    2)processes:进程数量,默认为1.

    app.run(processes=True)
    

    ps:多进程或多线程只能选择一个,不能同时开启

    使用示例:

      app.run(host=myaddr,port=myport,debug=False,threaded=True) ### threaded开启以后 不需要等队列 threaded=True
        #或者
        #app.run(host=myaddr,port=myport,debug=False,processes=3) ### processes=N 进程数量,默认为1个
    

    3.设置守护线程

    import time
    import threading
    
    def test():
        while True:
            print threading.currentThread()
            time.sleep(1)
    
    if __name__ == '__main__':
        t1 = threading.Thread(target=test)
        t1.setDaemon(True)  # python2.7设置
        t1.start()  
    ----------------------------------------------------------
    # python 3.7实现
    t1 = threading.Thread(target=ppp, args=(), daemon=True)
    t1.start()
    

    相关链接

    https://www.cxyzjd.com/article/xiaoyu_wu/102820384

    https://www.jb51.net/article/212169.htm

    https://cloud.tencent.com/developer/article/1572261

    https://www.cxyzjd.com/article/qq_33682575/105107041

    https://python-parallel-programmning-cookbook.readthedocs.io/zh_CN/latest/chapter4/02_Using_the_concurrent.futures_Python_modules.html

    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    搜索部分学习小结
    递归与搜索部分知识点小结
    匿名函数
    监督学习和非监督学习
    单变量线性回归
    神经网络(2)
    html
    javascript
    win10+celery4.x以上+redis的天坑
    Django-Views
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/15477236.html
Copyright © 2011-2022 走看看