Query Whether Python's Threading.lock Is Locked Or Not
Solution 1:
Sure!
>>>from threading import Lock>>>x = Lock()>>>x.locked()
False
>>>x.acquire()
True
>>>x.locked()
True
You could also do a non-blocking acquire:
x.acquire(False)
x.release()
In this case, if x
was unlocked then the code acquires it, and releases it. But if x was already locked, the non-blocking acquire returns at once (and returns False
), and we again release it. But that's subject to races! There's nothing to stop some other thread from releasing the lock between those two lines.
Ditto for checking .locked()
. That only tells you the state of the lock at the time .locked()
was executed. It may no longer be true by the time you execute the next statement.
By the way, the body of run()
is better written using the lock as a "context manager", like so:
defrun(self):
with aLock:
self.clip = subprocess.call([ 'mplayer', 'Avatar.h264'], stdin=subprocess.PIPE)
This does the acquire()/release()
pair for you, and is much more robust against unexpected exceptions raised in the body of the with
block (Python does all it can to release the lock if the body is exited for any reason).
Post a Comment for "Query Whether Python's Threading.lock Is Locked Or Not"