Python等价于Java的“tryLock”(惯用用法)?

2024-04-29 21:43:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在Java中,tryLock(long time, TimeUnit unit)可以用作获取锁的非阻塞尝试。如何在python中实现等效?(最好是Python式的| idiomatic方式!)在

Java tryLock公司:

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

Python锁:

^{pr2}$

Tags: newiftime方式公司unitjavalock1
2条回答

可以使用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。在

哎哟,我的错! 我应该先读一下pythonreference for Locks!在

Lock.acquire([blocking])

When invoked with the blocking argument set to False, do not block. If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return 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)

相关问题 更多 >