带有状态和超时的python锁定 [英] python lock with-statement and timeout
本文介绍了带有状态和超时的python锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用这样的Python 3序列:
I am using a Python 3 sequence like this:
lock = threading.Lock()
res = lock.acquire(timeout=10)
if res:
# do something ....
lock.release()
else:
# do something else ...
我宁愿使用with语句,而不要使用显式的获取"和释放",但是我不知道如何获得超时效果.
I would prefer to use a with-statement instead of explicit "acquire" and "release", but I don't know how to get the timeout effect.
推荐答案
您可以使用上下文管理器轻松完成此操作:
You can do this pretty easily with a context manager:
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 ...
* 注意:由于在 Lock.acquire
这篇关于带有状态和超时的python锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文