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

时间:2013-06-13 13:32:46

标签: python multithreading asynchronous locking nonblocking

在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) ?

2 个答案:

答案 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)

哎呀,我的坏! 我应该先阅读python reference for Locks

  

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)