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.