打赏

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

posted @ 2021-10-28 19:07  苍山落暮  阅读(4527)  评论(0编辑  收藏  举报