赞
踩
使用 threading.Event 对象关闭子线程
Event 是线程间通信的一种方式。其作用相当于1个全局flag,主线程通过控制 event 对象状态,来协调子线程步调。
class StartDecisionTread(threading.Thread): def __init__(self, ins): super(StartDecisionTread, self).__init__() self.ins = ins self.stop_event = threading.Event() def run(self): while not self.stop_event.is_set(): print(1) model_file_path = rf'1.db' if not os.path.exists(model_file_path): self.stop_event.set() #Python学习交流群:711312441 thread1 = StartDecisionTread(1) thread1.start()
子线程执行其任务循环,它每次循环都会检查event对象,该对象保持 false,就不会触发线程停止。
当主线程调用event对象的 set() 方法后,在子线程循环体内,调用event对象is_set()方法,发现event 对象为True后, 立即退出任务循环,结束运行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。