python 主线程停止执行子线程
使用threading.Thread创建子线程,有时候会遇到在主程序中中断子线程得场景,例如,主程序需要实时获取串口日志后对日志进行分析,就需要单独开启线程获取日志,当条件满足后,中断线程。本文描述得方法是使用threading.Event()事件进行线程间通信
import threading
import time
class Test_Stop_Thread():
def stop(self,_stop_event):
_stop_event.set() #set()方法是将flag值改为true,源代码中可见
def stopped(self,_stop_event):
return _stop_event.is_set() #检查当前得flag是否被设置
def run(self,_stop_event):
while not self.stopped(_stop_event): #轮询检查stopped返回值
# 以下为线程处理得业务代码
print("1")
ts = Test_Stop_Thread()
_stop_event = threading.Event() #创建线程通信,默认flag值是False
_stop_event.clear() #恢复默认值
t = threading.Thread(target=ts.run,args=(_stop_event,))#创建线程
t.start()#线程开始
time.sleep(1)
ts.stop(_stop_event) #触发结束
t.join()