python粗暴的杀死线程

import time
from threading import Thread
import threading
import time
import inspect
import ctypes

def main():
    while True:
        print("线程运行")
        time.sleep(1)

thr = Thread(target=main)
thr.start()


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)

print("开始")
time.sleep(4)
print("杀死线程")
stop_thread(thr)

作者 译文

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注