determine when a thread is waiting for a lock to release
multithreading, python, python-multithreading
Solution
You can use the optional `blocking` argument to the `Lock.acquire()` function, if you provide `False` for blocking like `Lock.acquire(False)`, the function will return `False` if the lock cannot be acquired (held by another thread) or it will acquire the lock and return `True`. You can use this with the following logic to determine if your thread will be blocking:
import threading
some_lock = threading.Lock()
# use this code anywhere you need to acquire the lock and check for blocking
if not some_lock.acquire(False):
print 'BLOCKING!'
some_lock.acquire() # call again with blocking=True (which is the default)
else:
print 'Acquired lock without blocking'
# lock has been acquired, make sure you release when done with critical section
The print statements are just there to show what is going on, replace this with whatever logic you want to use, for example maintaining a counter of times the thread blocked.
Problem
The lock mechanism (among others) exists to prevent access to shared resources at the same time by different threads. The thread that wants to use the resource is blocked, and must wait for lock to release in order to continue. (Correct me if I'm wrong) How can I tell when a thread is waiting for a lock to be released, and when not? In other words, how to know when a thread is blocked?. If this is possible, how can I tell how many times this occurs?