There is no direct way to do this with threading.Lock
objects that I know of. Those do have a locked
attribute, but that will show up as True
in all threads, not just the owning thread. It's possible with RLock
, but you have to access an internal __owner
attribute on the RLock object, which isn't advisable or guaranteed to always work. The code to do is would look like this, for what its worth:
#!/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()
Here's the output:
dan@dantop:~> ./test.py
I don't own the lock
Now I own the lock
I don't own the lock
But in reality, your code really shouldn't need to do this. Why do you feel like you need this explicit check? Typically when you're writing a block of code, you know whether or not a lock has been acquired in that context. Can you share an example where you think you need to check it?