在Java tryLock(long time, TimeUnit unit)中可以用作获取锁的非阻塞尝试。如何实现python中的等价物? (Pythonic | idiomatic方式首选!)
Java tryLock:
ReentrantLock lock1 = new ReentrantLock()
if (lock1.tryLock(13, TimeUnit.SECONDS)) { ... }
Python锁:
import threading
lock = Lock()
lock.acquire() # how to lock.acquire(timeout = 13) ?
答案 0 :(得分:4)
可以使用threading
模块Lock.acquire(False)
获取“尝试锁定”行为(请参阅Python doc):
import threading
import time
my_lock = threading.Lock()
successfully_acquired = my_lock.acquire(False)
if successfully_acquired:
try:
print "Successfully locked, do something"
time.sleep(1)
finally:
my_lock.release()
else:
print "already locked, exit"
我无法找到在这里使用with
的令人满意的方式。
答案 1 :(得分:2)
Lock.acquire([阻断])
在阻止参数设置为
False
的情况下调用时,请勿阻止。 如果阻止设置为True
的呼叫会阻止,请返回False
立即;否则,将锁定设置为锁定并返回True
。
所以我可以做这样的事情(或者更先进的事情:P):
import threading
import time
def my_trylock(lock, timeout):
count = 0
success = False
while count < timeout and not success:
success = lock.acquire(False)
if success:
break
count = count + 1
time.sleep(1) # should be a better way to do this
return success
lock = threading.Lock()
my_trylock(lock, 13)