Python 的多线程没有提供停止的方法,解决办法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao_5352269/article/details/81662099
def stop_smon():

    # 文件存在则停止线程
    print "停止检测中"
    # base_dir = os.path.join(os.path.dirname(__file__))
    # base_dir = os.path.dirname(os.path.realpath('__file__'))
    # 获取当前的目录
    base_dir = os.getcwd()
    print base_dir
    path = os.path.join(base_dir, 'stop')

    if not os.path.exists(path):
        # 查询所有的线程
        list = threading.enumerate()
        # os.remove(os.path.join(base_dir, 'stop'))
        for i in list:
            # 传递解释器退出异常
            _async_raise(i.ident, SystemExit)
    t = threading.Timer(5, stop_smon)
    t.start()

def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    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")

删除文件stop之后就会,使用 threading.enumerate()方法查询所有的线程,返回的是一个列表,通过该列表获取线程对象,ident方法获取该线程对象的标识符,同时传递SystemExit解释器请求退出.ctypes把参数转成相应的c_***类型.触发异常强制停止线程

猜你喜欢

转载自blog.csdn.net/zhao_5352269/article/details/81662099