我正在使用这样的
Python 3序列:
lock = threading.Lock() res = lock.acquire(timeout=10) if res: # do something .... lock.release() else: # do something else ...
解决方法
您可以使用上下文管理器轻松完成此操作:
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没有超时参数