28-python flask執行緒池用法
阿新 • • 發佈:2021-10-28
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
【勵志篇】: 古之成大事掌大學問者,不惟有超世之才,亦必有堅韌不拔之志。