上一篇博客中,殺死線程采用的方法是在線程中拋出異常 https://www.cnblogs.com/lucky-heng/p/11986091.html, 這種方法是強制殺死線程,但是如果線程中涉及獲取釋放鎖,可能會導致死鎖。
有一種更優雅的殺死線程的方法就是使用退出標記,這里使用threading.Event()創建一個事件管理標記flag,這種方法是更安全的。
# encoding:utf-8 import time import threading class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self, *args, **kwargs): super(StoppableThread, self).__init__(*args, **kwargs) self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() def run(self): print("begin run the child thread") while True: print("sleep 1s") time.sleep(1) if self.stopped(): # 做一些必要的收尾工作 break if __name__ == "__main__": print("begin run main thread") t = StoppableThread() t.start() time.sleep(3) t.stop() print("main thread end")