import threading import time import ctypes import inspect __all__ = ["stop_thread"] def __async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread): """ stop thread""" __async_raise(thread.ident, SystemExit) def demo_fun(): while True: print(123456) def main_test(): t1 = threading.Thread( target=demo_fun, daemon=False ) print("开始开始1") t1.start() try: time.sleep(1) raise RuntimeError except: stop_thread(t1) print("开始开始2") print(999999999999) if __name__ == '__main__': main_test()
原创文章,转载请注明出处:http://124.221.219.47/article/637863/