Py学习  »  Sujania Wayne Ye  »  全部回复
回复总数  1
9 年前
回复了 Sujania Wayne Ye 创建的主题 » 强制退出运行python中的线程[duplicate]

这是基于 thread2 -- killable threads (Python recipe)

您需要调用Pythreadstate_setAsyncExc(),它仅通过cTypes可用。

这只在Python2.7.3上进行过测试,但它很可能适用于其他最近的2.x版本。

import ctypes

def terminate_thread(thread):
    """Terminates a python thread from another thread.

    :param thread: a threading.Thread instance
    """
    if not thread.isAlive():
        return

    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent 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(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")