✍45 使用ctypes终止线程

from threading import Thread
import time
import inspect
import ctypes


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:
        # """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):
    thread._is_stopped = True  # 修改线程状态
    _async_raise(thread.ident, SystemExit)


def task():
    for i in range(1, 100):
        print(i)
        time.sleep(1)


if __name__ == '__main__':
    th = Thread(target=task)
    th.start()  # 开始线程
    print(th.is_alive())  # 查看线程运行状态
    time.sleep(2)
    stop_thread(th)  # 终止线程
    print(th.is_alive())  # 查看线程运行状态

多种方法实现

原文地址:https://www.cnblogs.com/songhaixing/p/15607208.html