python多线程 主线程等待子线程

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('/')
def run_jobs():
    # 交由线程去执行耗时任务
    executor.submit(long_task, 'hello', 123)
    return 'long task running.'

# 耗时任务
def long_task(arg1, arg2):
    print("args: %s %s!" % (arg1, arg2))
    sleep(10)
    print("Task is done!")


if __name__ == '__main__':
    app.run()

主线程等待子线程 

from time import ctime
import threading
import time


def a():
    # for i in range(5):
    print('Program a is running... at ', ctime(), u'.线程名为:', threading.current_thread().name)
    time.sleep(0.2)


def b(x):
    # for i in range(5):
    print('Program b(' + x + ') is running... at ', ctime(), u'.线程名为:', threading.current_thread().name)
    time.sleep(0.1)


if __name__ == '__main__':
    print('Mainthread %s is running...' % threading.current_thread().name)
    thread_list = []
    for i in range(400):  # 同时运行多个
        t1 = threading.Thread(target=a)
        thread_list.append(t1)

    t2 = threading.Thread(target=b, args=('Python',))
    thread_list.append(t2)
    t3 = threading.Thread(target=b, args=('Java',))
    thread_list.append(t3)

    for t in thread_list:
        t.setDaemon(True)  # 设置为守护线程,不会因主线程结束而中断
        t.start()
    for t in thread_list:
        t.join()  # 子线程全部加入,主线程等所有子线程运行完毕

    print('Mainthread %s ended.' % threading.current_thread().name)

注意:

当循环开启多个耗时线程,中间最好加个睡眠,避免卡死!!! 

你可能感兴趣的:(Flask框架,flask,python,后端)