Bootstrap

python多线程:不堵塞主线程+子线程超时结束

import threading
import time


class LongTimeTool(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.is_timeout = False

    def long_time_fun(self):
        print("long_time_fun start")
        # 模拟需要执行的耗时操作
        while not self.is_timeout:
            print("我在运行")
            time.sleep(1)
        print("long_time_fun end")


def async_fun():
    # 创建线程并启动
    thread = threading.Thread(target=async_fun_son)
    thread.start()
    time.sleep(1)
    return "返回response"


def async_fun_son():
    print("async_fun_son start")
    long_time_tool = LongTimeTool()
    thread_son = threading.Thread(target=long_time_tool.long_time_fun)
    thread_son.start()
    time.sleep(5)
    long_time_tool.is_timeout = True
    thread_son.join()
    print("async_fun_son end")


if __name__ == '__main__':
    print("开始")
    print(async_fun())
    time.sleep(20)
    print("结束")


;