python3 线程死锁
所谓死锁:是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程,如下就是死锁
code
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() print('\033[42m%s 解B锁\033[0m' %self.name) mutexA.release() print('\033[42m%s 解A锁\033[0m' %self.name) 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() print('\033[42m%s 解A锁\033[0m' %self.name) mutexB.release() print('\033[42m%s 解B锁\033[0m' %self.name) if __name__ == '__main__': for i in range(10): t=MyThread() t.start()
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py Thread-1 拿到A锁 Thread-1 拿到B锁 Thread-1 解B锁 Thread-1 解A锁 Thread-1 拿到B锁 Thread-2 拿到A锁 ^CException ignored in: <module 'threading' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1308, in _shutdown lock.acquire() KeyboardInterrupt macname@MacdeMacBook-Pro py %
线程1拿到A以及B后,再次释放
接下来,由于线程2抢到了A锁,线程1抢到了B锁
相互等待,两个线程都无法继续执行