有没有小伙伴被线程无法终止烦到吧,有时候真的是气的你想把电脑砸了,我也是,不要再跟我说如何优雅的退出了,实在让你心烦那就ctypes杀死它!该出手时还是得出手,快刀斩乱麻。这就来看一下到底有多快…
import threading
import time
import inspect
import ctypes
def _async_raise(tid, exctype):
'''###Python学习交流Q群:906715085###
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 mythread():
while 1:
print("in thread ...")
if __name__ == "__main__":
t = threading.Thread(target=mythread)
t.start() print("Start")
time.sleep(5)
stop_thread(t)
print("stoped")
代码也就二十多行,真的是代码界少有的了。虽然代码不是密密麻麻的,但是点赞才是真情呀!!这一篇就到这里了,想看下一篇吗?