Python 获取阻塞锁是否被阻塞

Python 获取阻塞锁是否被阻塞,python,python-3.x,multithreading,thread-safety,race-condition,Python,Python 3.x,Multithreading,Thread Safety,Race Condition,在Python3中,我希望获得一个锁,然后知道它是否被阻止。问题是threading.Lock.acquire如果使用blocking=True调用,则总是返回True,因此无法判断在调用函数时锁是否已锁定。以这段代码为例: import threading foo = None lock = threading.Lock() def bar(): global foo # Only compute foo in one thread at a time. if no

在Python3中,我希望获得一个锁,然后知道它是否被阻止。问题是
threading.Lock.acquire
如果使用
blocking=True
调用,则总是返回
True
,因此无法判断在调用函数时锁是否已锁定。以这段代码为例:

import threading

foo = None
lock = threading.Lock()

def bar():
    global foo
    # Only compute foo in one thread at a time.
    if not lock.acquire(blocking=False):
        # The race condition exists here.
        # Another thread is already computing foo.
        # This instance does not need to recompute foo.
        # Wait for that instance to finish.
        with lock:
            # Just return the value that the other instance computed.
            return foo
    # No other instance of this function is computing foo.
    with lock:
        # Compute foo.
        foo = [something]
        return foo
这里的问题是,如果上面代码中的注释表示存在竞争条件,则可以再次获取
lock

如果这是因为第三个线程位于函数中的同一点,首先继续并获取锁,那么这是不可取的,因为它引入了一个轻微的延迟。确实没有理由需要保护
return foo
;两个线程应该能够同时执行此操作

但是,如果获取是由于另一个线程重新计算
foo
,则这是不可取的,因为一旦释放锁,
foo
将发生更改。函数应返回调用时计算的
foo
值。如果
foo
发生更改,那么它将无法再返回该值


理想情况下,我们会有一个
acquire
函数,它可以阻止并仍然返回它是否被阻止。这样,我们可以自信地断言,函数总是返回调用函数时正在计算的
foo
的值,并且只有当
foo
尚未计算时,函数才会继续计算,并返回新值。这可以用Python实现吗?

您是否尝试过
lock.lock()
?@Sraw-Hm,不,那是什么?我没有在上面看到它。嗯,
返回锁的状态:如果某个线程获取了锁,则返回True;如果没有,则返回False。
@Sraw这与
非锁。获取(False)
有何不同?如果锁被锁定,它就不会阻塞。嗯。。。不,你的情况没什么不同。我只是根据你的头衔发表评论。诚然,我不完全理解你的描述。如果线程在计算后释放锁,
foo
仍将在下一次调用中重新计算。您如何确定是否需要计算它?如果foo:\n return foo足够,可能是正常的