死锁与递归锁
作者:互联网
from threading import Thread,Lock import time mutexA=Lock() mutexB=Lock() class MyThread(Thread): def run(self): self.func1() self.func2() def func1(self): mutexA.acquire() print('\033[41m%s 拿到A锁\033[0m' %self.name) mutexB.acquire() print('\033[42m%s 拿到B锁\033[0m' %self.name) mutexB.release() mutexA.release() def func2(self): mutexB.acquire() print('\033[43m%s 拿到B锁\033[0m' %self.name) time.sleep(2) mutexA.acquire() print('\033[44m%s 拿到A锁\033[0m' %self.name) mutexA.release() mutexB.release() if __name__ == '__main__': for i in range(10): t=MyThread() t.start()
死锁↑ 递归锁↓
from threading import Lock,Thread,RLock import time mutexB=mutexA=RLock() #同一把锁锁 class MyThread(Thread): def run(self): self.f1() self.f2() def f1(self): mutexA.acquire() print('拿到A锁',self.name) mutexB.acquire() print('拿到B锁',self.name) mutexB.release() mutexA.release() def f2(self): mutexB.acquire() print('拿到B锁', self.name) mutexA.acquire() print('拿到A锁', self.name) mutexA.release() mutexB.release() if __name__ == '__main__': for i in range(10): t = MyThread() t.start()
标签:__,name,递归,self,死锁,mutexA,mutexB,033 来源: https://blog.51cto.com/52770825/2795064