gpt4 book ai didi

Python 相当于 Java 的 `tryLock`(惯用语)?

转载 作者:太空狗 更新时间:2023-10-30 02:21:17 27 4
gpt4 key购买 nike

Java tryLock(long time, TimeUnit unit)可以用作获取锁的非阻塞尝试。如何实现python中的等价物? (首选 Pythonic | idiomatic 方式!)

Java 尝试锁:

ReentrantLock lock1 = new ReentrantLock()
if (lock1.tryLock(13, TimeUnit.SECONDS)) { ... }

Python 锁:

import threading
lock = Lock()
lock.acquire() # how to lock.acquire(timeout = 13) ?

最佳答案

可以使用 threading 模块的 Lock.acquire(False) 获得“try lock”行为(参见 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

关于Python 相当于 Java 的 `tryLock`(惯用语)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com