python 杀死线程的两种方式
Posted 程序媛小菇凉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 杀死线程的两种方式相关的知识,希望对你有一定的参考价值。
方法一:强制杀死
import threading import time import inspect import ctypes def _async_raise(tid, exctype): if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread): _async_raise(thread.ident, SystemExit) class TestThread(threading.Thread): def run(self): print("begin run the child thread") while True: print("sleep 1s") time.sleep(1) if __name__ == "__main__": print("begin run main thread") t = TestThread() t.start() time.sleep(3) stop_thread(t) print("main thread end")
方法二:优雅杀死
# 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")
以上是关于python 杀死线程的两种方式的主要内容,如果未能解决你的问题,请参考以下文章