Recursive lock
The first case: a lock with a thread lock many times, does not affect the execution
from threading import RLock,currentThread,Thread
r = RLock()
r.acquire()
r.acquire()
print("over")
over
The second case: Multithreaded must ensure that the number of locking and unlocking of the same number, other threads to be able to grab the lock
from threading import RLock,currentThread,Thread
import time
r = RLock()
def task():
#r.acquire() # 如果增加这行代码,程序将无法结束
r.acquire()
time.sleep(2)
print(currentThread().name)
r.release() # 只释放了一次,但加锁了两次
def task2():
r.acquire() # 出现了死锁的情况
time.sleep(2)
print(currentThread().name)
r.release()
Thread(target=task).start()
Thread(target=task2).start()
Thread-1
Thread-2
to sum up:
- The same thread of the same lock locked many times, does not affect the execution
- We must ensure that the same thread, the number of locked and unlocked same number of times, other threads to be able to grab the lock