from threading import Thread, Lock, RLock import time mutexA = Lock() muteXB = Lock()
'''
# 将上述的
mutexA = Lock()
mutexB = Lock()
# 换成
mutexA = mutexB = RLock() # 递归锁 可解决本例的死锁问题
'''
class MyThead(Thread): def run(self) -> None: self.func1() self.func2() def func1(self): mutexA.acquire() print('%s 抢到A锁'%self.name) # 获取当前线程名 muteXB.acquire() print('%s 抢到B锁'%self.name) muteXB.release() mutexA.release() def func2(self): muteXB.acquire() print('%s 抢到B锁' % self.name) time.sleep(2) mutexA.acquire() print('%s 抢到A锁' % self.name) mutexA.release() muteXB.release() ''' Thread-1 抢到A锁 Thread-1 抢到B锁 Thread-1 抢到B锁 Thread-2 抢到A锁 线程1接下来要抢A锁,但A锁在线程2那里 线程2接下来要抢B锁,但B锁在线程1那里 形成死锁 ''' if __name__ == '__main__': for i in range(10): t = MyThead() t.start()
标签:线程,Thread,递归,self,死锁,抢到,muteXB,mutexA,name From: https://www.cnblogs.com/palx/p/17208113.html