5

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

Java tryLock:

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

蟒蛇锁:

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

2 回答 2

7

可以使用模块获得“尝试锁定”行为(请参阅Python 文档):threadingLock.acquire(False)

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这里。

于 2014-01-21T10:12:59.837 回答
1

哎哟,我的坏!我应该先阅读关于 Locks 的 Python 参考资料

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)
于 2013-06-13T13:32:45.697 回答