Python死锁与递归锁

时间:2022-02-09 23:51:45

Lock() 互斥锁会导致死锁,用RLock()递归锁代替。

递归锁:可以连续acquire多次,每acquire一次计数器+1(无论acquire的是哪个锁),只有计数为0才能被acquire

mutexB = mutexA = RLock()

class MyThread(Thread):
def run(self):
self.f1()
self.f2() def f1(self):
mutexA.acquire()
print('%s 拿到了A锁'%self.name)
mutexB.acquire()
print('%s 拿到了B锁'%self.name)
mutexB.release()
mutexA.release() def f2(self):
mutexB.acquire()
print('%s 拿到了B锁'%self.name) #递归锁计数不为0,其他线程就无法取得递归锁
mutexA.acquire()
print('%s 拿到了A锁'%self.name)
mutexA.release()
mutexB.release() if __name__ == "__main__":
for i in range(0, 10):
my_thread = MyThread()
my_thread.start()