zoukankan      html  css  js  c++  java
  • Python 为threading.Thread添加 terminate

    import threading
    import inspect
    import ctypes
    
    
    def _async_raise(tid, exc_type):
        """raises the exception, performs cleanup if needed"""
        if not inspect.isclass(exc_type):
            raise TypeError("Only types can be raised (not instances)")
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exc_type))
        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, 0)
            raise SystemError("PyThreadState_SetAsyncExc failed")
    
    
    class Thread(threading.Thread):
        def raise_exc(self, exc_type):
            """raises the given exception type in the context of this thread"""
            _async_raise(ctypes.c_long(self.ident), exc_type)
    
        def terminate(self):
            """raises SystemExit in the context of the given thread, which should
            cause the thread to exit silently (unless caught)"""
            self.raise_exc(SystemExit)
  • 相关阅读:
    ANSI C 与 C99的不同
    字符串中含有空格的注意事项
    巧用printf函数
    求数列的和
    数值统计
    平方和与立方和
    求奇数的乘积
    第几天?
    细节之重
    用%*c滤掉回车,ASCII码排序
  • 原文地址:https://www.cnblogs.com/stones/p/7358097.html
Copyright © 2011-2022 走看看