Query whether Python's threading.Lock is locked or not

前端 未结 1 1866
醉梦人生
醉梦人生 2021-02-07 07:13

I have a thread I am running (code below) which launches a blocking subprocess. To ensure that other threads do not launch the same subprocess, I have a lock around this s

1条回答
  •  太阳男子
    2021-02-07 07:42

    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:

    def run(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).

    0 讨论(0)
提交回复
热议问题