python-3.x – python lock with-statement和timeout

前端之家收集整理的这篇文章主要介绍了python-3.x – python lock with-statement和timeout前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用这样的 Python 3序列:
lock = threading.Lock()
res = lock.acquire(timeout=10)
if res:
    # do something ....
    lock.release()
else:
    # do something else ...

我更喜欢使用with语句而不是显式的“获取”和“释放”,但我不知道如何获得超时效果.

解决方法

您可以使用上下文管理器轻松完成此操作:
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中不起作用,因为Lock.acquire没有超时参数

原文链接:https://www.f2er.com/python/242035.html

猜你在找的Python相关文章