我正在使用这样的Python 3序列:
lock = threading.Lock()
res = lock.acquire(timeout=10)
if res:
# do something ....
lock.release()
else:
# do something else ...
我更喜欢使用with语句而不是显式“获取”和“释放”,但我不知道如何获得超时效果。
答案 0 :(得分:8)
您可以使用上下文管理器轻松完成此操作:
import threading
from contextlib import contextmanager
@contextmanager
def acquire_timeout(lock, timeout):
result = lock.acquire(timeout=timeout)
yield result
if result:
lock.release()
# Usage:
lock = threading.Lock()
with acquire_timeout(lock, 2) as acquired:
if acquired:
print('got the lock')
# do something ....
else:
print('timeout: lock not available')
# do something else ...
* 注意:这在Python 2.x中不起作用,因为timeout
没有Lock.acquire
参数
答案 1 :(得分:2)
稍微好一点的版本:
import threading
from contextlib import contextmanager
class TimeoutLock(object):
def __init__(self):
self._lock = threading.Lock()
def acquire(self, blocking=True, timeout=-1):
return self._lock.acquire(blocking, timeout)
@contextmanager
def acquire_timeout(self, timeout):
result = self._lock.acquire(timeout=timeout)
yield result
if result:
self._lock.release()
def release(self):
self._lock.release()
# Usage:
lock = TimeoutLock()
with lock.acquire_timeout(3) as result:
if result:
print('got the lock')
# do something ....
else:
print('timeout: lock not available')
# do something else ...
看来你不能继承threading.Lock
,所以我不得不改造包装类。