多线程的timeout

def with_timeout(timeout=0, exception=TTimeout):
    def async_raise(target_tid, exc):
        """Raises an asynchronous exception in another thread.
        Read http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc
        for further enlightenments.
        coped from stopit
        :param target_tid: target thread identifier
        :param exc: Exception class to be raised in that thread
        """
        ret = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(target_tid),
                                                         ctypes.py_object(exc))
        if ret == 0:
            raise ValueError("Invalid thread ID {}".format(target_tid))
        elif ret > 1:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), None)
            raise SystemError("PyThreadState_SetAsyncExc failed")

    class MyTimer(object):
        def __init__(self, time_out=0, exc=TTimeout):
            """
            :param time_out: time out seconds
            :param exc: when time out occur raise exc out
            """
            self.target_tid = threading.current_thread().ident
            self.timer = None  # PEP8
            self.time_out = time_out
            self.exception = exc

        def __shut_down(self):
            async_raise(self.target_tid, self.exception)

        def __start(self):
            self.timer = threading.Timer(timeout, self.__shut_down)
            timer.start()

        def __enter__(self):
            self.__start()
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            self.timer.cancel()
            return False

    def deco(func):

        @wraps(func)
        def wraper(*args, **kwargs):
            """
            using __enter__ and __exit__ to ensure when the thread async_raised,
            it is aliving

            it will raise any exception from func
            """
            result = None
            with MyTimer(timeout, exception) as mytimer:
                result = func(*args, **kwargs)
            return result

        return wraper

    return deco

用法:

@with_timeout(2)
def loop_test(t=2):
    last_time = time.time()
    while True:
        if time.time() - last_time > t:
            break
        time.sleep(t * 0.1 / 10.0)

核心方法抄的,不过这里面对try expect finally 和__enter__,__exit__有了深度认识,很开心

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值