How to implement a Lock with a timeout in Python 2.7

前端 未结 7 827
执笔经年
执笔经年 2020-12-03 07:09

Is there a way to implement a lock in Python for multithreading purposes whose acquire method can have an arbitrary timeout? The only working solutions I found

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 07:43

    If somebody needs Python >= 3.2 API:

    import threading
    import time
    
    
    class Lock(object):
        _lock_class = threading.Lock
    
        def __init__(self):
            self._lock = self._lock_class()
            self._cond = threading.Condition(threading.Lock())
    
        def acquire(self, blocking=True, timeout=-1):
            if not blocking or timeout == 0:
                return self._lock.acquire(False)
            cond = self._cond
            lock = self._lock
            if timeout < 0:
                with cond:
                    while True:
                        if lock.acquire(False):
                            return True
                        else:
                            cond.wait()
            else:
                with cond:
                    current_time = time.time()
                    stop_time = current_time + timeout
                    while current_time < stop_time:
                        if lock.acquire(False):
                            return True
                        else:
                            cond.wait(stop_time - current_time)
                            current_time = time.time()
                    return False
    
        def release(self):
            with self._cond:
                self._lock.release()
                self._cond.notify()
    
        __enter__ = acquire
    
        def __exit__(self, t, v, tb):
            self.release()
    
    
    class RLock(Lock):
        _lock_class = threading.RLock
    

提交回复
热议问题