本文主要是介绍pythons强行杀掉线程的方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用ctypes强行杀掉线程
import threading
import time
import inspect
import ctypes def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" tid = ctypes.c_long(tid) 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): _async_raise(thread.ident, SystemExit) def print_time(): while 2: print(111111111111) print(222222222222) print(333333333333) print(444444444444) print(555555555555) print(666666666666) if __name__ == "__main__": t = threading.Thread(target=print_time) t.start() stop_thread(t) print("stoped") while 1: pass
- 这个方法是在网上找的,推荐一下,非常干净利索的干掉了子线程。
这篇关于pythons强行杀掉线程的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!