美文网首页
Python强制杀死线程

Python强制杀死线程

作者: xieyan0811 | 来源:发表于2022-03-27 20:02 被阅读0次
import ctypes
import inspect
import time
from threading import Thread

def _async_raise(tid, exctype):
    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:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):
    print(f'\nt -> {thread}')
    print(f'\nthread.ident -> {thread.ident}')
    _async_raise(thread.ident, SystemExit)
    thread.join()

def func1():
    while True:
        try:
            print(f'func1')
            time.sleep(1)
        except SystemExit:
            print("!!!!")
            sys.exit()
        except:
            print(traceback.format_exc())

i = Thread(target=func1, args=())
i.start()
time.sleep(3)
print(f'线程{i}的状态{i.is_alive()}, 线程{i}的名字{i.name}, 线程的方法{i.ident}')
print(type(i.name), i.name)
stop_thread(i)

相关文章

网友评论

      本文标题:Python强制杀死线程

      本文链接:https://www.haomeiwen.com/subject/ryiyjrtx.html