flask線程池用法
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
