Skip to main content
 首页 » 编程设计

python如何知道当前线程是否持有锁

2025年05月04日43insus

我有一个 threading.Lock 对象,我想知道 current_thread 是否持有这个锁。实现这一目标的最简单方法是什么?

请您参考如下方法:

据我所知,对于 threading.Lock 对象,没有直接的方法可以做到这一点。那些确实有一个 locked 属性,但它会在所有线程中显示为 True,而不仅仅是拥有线程。使用 RLock 是可能的,但您必须访问 RLock 对象上的内部 __owner 属性,这是不可取的或保证始终有效。要做的代码看起来像这样,因为它的值(value):

#!/usr/bin/python 
 
import threading 
import time 
 
def worker(): 
    if l._RLock__owner is threading.current_thread(): 
        print "I own the lock" 
    else: 
        print "I don't own the lock" 
    l.acquire() 
    if l._RLock__owner is threading.current_thread(): 
        print "Now I own the lock" 
    else: 
        print "Now I don't own the lock" 
    time.sleep(5) 
    l.release() 
 
if __name__ == "__main__": 
    l = threading.RLock() 
    thds = [] 
    for i in range(0, 2):  
        thds.append(threading.Thread(target=worker)) 
        thds[i].start() 
 
    for t in thds: 
        t.join() 

这是输出:

dan@dantop:~> ./test.py 
I don't own the lock 
Now I own the lock 
I don't own the lock 

但实际上,您的代码确实不需要这样做。为什么你觉得你需要这个明确的检查?通常,当您编写代码块时,您知道在该上下文中是否已获取锁。您能否分享一个您认为需要检查的示例?