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

Rah*_*hul 1 python multithreading python-multithreading python-2.7

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

dan*_*ano 6

threading.Lock对于我所知道的对象,没有直接的方法可以做到这一点.那些确实有一个locked属性,但是会出现True在所有线程中,而不仅仅是拥有线程.这是可能的RLock,但您必须访问__ownerRLock对象的内部属性,这是不可取的或保证始终有效.要做的代码看起来像这样,它的价值是什么:

#!/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()
Run Code Online (Sandbox Code Playgroud)

这是输出:

dan@dantop:~> ./test.py
I don't own the lock
Now I own the lock
I don't own the lock
Run Code Online (Sandbox Code Playgroud)

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