python 死锁
""" 死锁 要AB两个锁 当A锁内部需要使用B锁,同时B锁内部需要使用A锁的时候,就要可能会出现死锁 出现死所的解决方法: 1.重构代码 2.添加timeout时间 下面代码中要可能返回下面内容,在同时认为锁被对方占用,同时释放 Thread-1获取到a锁 Thread-2获取到b锁 over """ import time from threading import Thread, Lock lock_a = Lock() lock_b = Lock() class MyThread(Thread): def run(self) -> None: if lock_a.acquire(): # 如果a锁可以获取到,返回True,获取不到就阻塞 print(self.name + "获取到a锁") time.sleep(0.1) if lock_b.acquire(timeout=0.01): # 这里不加退出时间就会要可能出现死锁 print(self.name + "获取到b锁,现有ab锁") lock_b.release() lock_a.release() class MyThread1(Thread): def run(self) -> None: if lock_b.acquire(): # 如果b锁可以获取到,返回True,获取不到就阻塞 print(self.name + "获取到b锁") time.sleep(0.1) if lock_a.acquire(timeout=0.01): # 这里不加退出时间就会要可能出现死锁 print(self.name + "获取到a锁,现有ab锁") lock_a.release() lock_b.release() if __name__ == ‘__main__‘: t1 = MyThread() t2 = MyThread1() t1.start() t2.start() t1.join() t2.join() print("over")
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16