死锁:
所谓死锁,就是指俩个或俩个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法说推进下去
import threading,time class myThread(threading.Thread): def doA(self): lockA.acquire() print(self.name,"getlockA",time.ctime()) time.sleep(3) lockB.acquire() print(self.name,'getlockB',time.ctime()) lockB.release() lockA.release() def doB(self): lockB.acquire() print(self.name,"getlockB",time.ctime()) time.sleep(3) lockA.acquire() print(self.name,'getlockA',time.ctime()) lockA.release() lockB.release() def run(self): self.doA() self.doB() if __name__ == "__main__": lockA = threading.Lock() lockB = threading.Lock() threads = [] for i in range(5): threads.append(myThread()) for t in threads: t.start() for t in threads: t.join() =============================== Thread-1 getlockA Fri May 24 23:30:18 2019 Thread-1 getlockB Fri May 24 23:30:21 2019 Thread-2 getlockA Fri May 24 23:30:21 2019 Thread-1 getlockB Fri May 24 23:30:21 2019
注意:Thread-1 开始执行的时候,执行完doA的时候,释放了lockA与lockB. 同Thread-1开始执行doB的时候,因为这个时间是没有同步锁的,所以Thread-2也可以执行doA了。这时Thread-1拿 到了lockB,同时
Thread-2 拿到lockA.当Thread-1走到doB的第二步,他要想拿lockA,但是lockA在Thread-2身上,没有释放,Thread-1拿不到lockA,只有等待。。。。Thread-2走doA的第二步时,他要拿lockB.但是lockB
在Thread-1身上,没有释放,Thread-2拿不到lockB,也只有等待。 这样在没有外力的情况下,这个程序就等死了。。。。。
这就是死锁产生的原因。
threading.RLock是递归锁
递归锁就是调用threading下的RLock类功能实现的,RLock它自带有计数功能,每让线程获取到以后就会就进行自加一的功能(RLock默认数值是0,只要RLock不是0线程就不能进行获取),
只要进行一进行释放功能RLock就会进行自减一的功能直到为0时。
import threading,time class myThread(threading.Thread): def doA(self): lock.acquire() print(self.name,"getlockA",time.ctime()) time.sleep(3) lock.acquire() print(self.name,'getlockB',time.ctime()) lock.release() lock.release() def doB(self): lock.acquire() print(self.name,"getlockB",time.ctime()) time.sleep(3) lock.acquire() print(self.name,'getlockA',time.ctime()) lock.release() lock.release() def run(self): self.doA() self.doB() if __name__ == "__main__": # lockA = threading.Lock() # lockB = threading.Lock() lock = threading.RLock() #threading.RLock是递归锁,根据时间来的,就可以解决死锁问题 threads = [] for i in range(5): threads.append(myThread()) for t in threads: t.start() for t in threads: t.join()