Home  >  Q&A  >  body text

threadingtest - python threading中的lock rlock 为何rlock可以调用多次acquire

在python的多线程中,使用threading中的lock rlock锁, 为何rlock可以调用多次acquire,lock缺不能,lock调用多次而且会发生死锁,rlock不会,求大神指点下

阿神阿神2741 days ago601

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-18 10:33:29

    rlock is a reentrant lock. You can simply understand that it comes with a counter. Acquire has a counter of +1, and release has a counter of -1. Negative values ​​are not allowed, otherwise an exception will occur.

    Why do we do this? Because the application scenarios are different, a reentrant lock can call another method that requires the lock, but a non-reentrant lock cannot do this.

    def fun1():
        rlock.acquire()
        fun2()
        rlock.release()
    
    def fun2():
        rlock.acquire()
        rlock.release()

    reply
    0
  • PHPz

    PHPz2017-04-18 10:33:29

    The difference between lock and rlock is r:
    reentrant, can be entered repeatedly. A thread can acquire the same rlock multiple times without being blocked. If a thread acquires rlock multiple times, it must release the same number of times before it can be released. rlock.

    Lock is different. It can only be acquired once and cannot be acquired again before it is released.

    For more information, please refer to this answer:
    http://stackoverflow.com/ques...

    reply
    0
  • Cancelreply