本文主要是介绍python多线程:不堵塞主线程+子线程超时结束,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import threading
import timeclass LongTimeTool(threading.Thread):def __init__(self):threading.Thread.__init__(self)self.is_timeout = Falsedef 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 = Truethread_son.join()print("async_fun_son end")if __name__ == '__main__':print("开始")print(async_fun())time.sleep(20)print("结束")
这篇关于python多线程:不堵塞主线程+子线程超时结束的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!