The official definition of

Lock: an original lock that does not belong to a specific thread. That is, one thread can unlock the lock by another thread

Similarity: Lock, rlock support context manager, can use with instead of acquire Release operation

Common use

  1. The lock can be released by another thread
import threading

lock = threading.Lock()
lock.acquire()

def func():
    lock.release()
    print("lock is released")

t = threading.Thread(target=func)
t.start()
Copy the code
  1. With context manager
import threading
import time

lock1 = threading.RLock()

def outer():
    with lock1:
        print("outer function:%s" % threading.current_thread())
 

if __name__ == "__main__":
    t1 = threading.Thread(target=outer)
    t2 = threading.Thread(target=outer)
    t1.start()
    t2.start()
Copy the code
  1. When will rlock be used
import threading
import time

lock1 = threading.RLock()


def inner():
    with lock1:
        print("inner1 function:%s" % threading.current_thread())


def outer():
    print("outer function:%s" % threading.current_thread())
    with lock1:
        inner()


if __name__ == "__main__":
    t1 = threading.Thread(target=outer)
    t2 = threading.Thread(target=outer)
    t1.start()
    t2.start()
Copy the code

In general, the nesting of locks like this cannot be satisfied with ordinary locks, because the lock can only acquire once, after the use of release. Only this rlock can be reentrant, otherwise deadlock occurs when using lock.