1. 排斥锁可能会造成死锁,先看看死锁的现象
from threading import Thread,Lock import time mutexA=Lock() mutexB=Lock() 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) time.sleep(0.1) mutexA.acquire() print(‘%s 拿到了A锁‘ % self.name) mutexA.release() mutexB.release() if __name__ == ‘__main__‘: for i in range(10): t=MyThread() t.start()
运行结果:
Thread-1 拿到了A锁 Thread-1 拿到了B锁 Thread-1 拿到了B锁 Thread-2 拿到了A锁 卡住了。。。。。。
2. 互斥锁Lock,只能acquire()一次, 递归锁RLock可以acquire()多次
# 互斥锁只能acquire一次 from threading import Thread from threading import Lock mutexA=Lock() mutexA.acquire() print(1) mutexA.acquire() print(2) mutexA.release() 运行结果: 1 #输出1后卡在第二个mutexA.acquire()上
# 递归锁可以acquire多次 from threading import Thread,Lock from threading import RLock mutexA=RLock() mutexA.acquire() mutexA.acquire() mutexA.release() 正常运行!
3. 递归锁的应用
# 递归锁:可以连续acquire多次,每acquire一次计数器+1,只有计数为0时,才能被抢到acquire from threading import Thread,RLock import time 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) time.sleep(7) mutexA.acquire() print(‘%s 拿到了A锁‘ % self.name) mutexA.release() mutexB.release() if __name__ == ‘__main__‘: for i in range(10): t=MyThread() t.start()
原文地址:https://www.cnblogs.com/beallaliu/p/9191694.html
时间: 2024-11-08 21:43:14