python线程死锁与递归锁
死锁现象
所谓死锁: 是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。
此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程,如下就是死锁
from threading import Thread,Lock
import time
mutexA = Lock()
mutexB = Lock()
class MyThread(Thread):
def run(self):
self.task1()
self.task2()
def task1(self):
mutexA.acquire()
print('%s task1 get A' %self.name)
mutexB.acquire()
print('%s task1 get B' % self.name)
mutexB.release()
mutexA.release()
def task2(self):
mutexB.acquire()
print('%s task2 get B' % self.name)
time.sleep(1) # Thread-2 拿到执行权,执行get A出现死锁,此时thread2需要B锁,而thread1占用,与此同时,thread1需要A锁,thread2占用
mutexA.acquire()
print('%s task2 get A' % self.name)
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(10):
t = MyThread()
t.start()
-------------------输出
Thread-1 task1 get A
Thread-1 task1 get B
Thread-1 task2 get B
Thread-2 task1 get A # 出现死锁,整个程序被阻塞
递归锁
解决方法,递归锁,在Python中为了支持在同一线程中多次请求同一资源,python提供了可重入锁RLock。
这个RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源可以被多次require。
直到一个线程所有的acquire都被release,其他的线程才能获得资源。上面的例子如果使用RLock代替Lock,则不会发生死锁,二者的区别是:递归锁可以连续acquire多次,而互斥锁只能acquire一次
from threading import Thread,RLock
import time
mutexA = mutexB = RLock()
class MyThread(Thread):
def run(self):
self.task1()
self.task2()
def task1(self):
mutexA.acquire()
print('%s task1 get A' %self.name)
mutexB.acquire()
print('%s task1 get B' % self.name)
mutexB.release()
mutexA.release()
time.sleep(1) # Thread-2 拿到执行权,,此时counter=0,thread2执行task1
def task2(self):
mutexB.acquire()
print('%s task2 get B' % self.name)
mutexA.acquire()
print('%s task2 get A' % self.name)
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(10):
t = MyThread()
t.start()
------------------------输出
Thread-1 task1 get A
Thread-1 task1 get B
Thread-2 task1 get A
Thread-2 task1 get B
Thread-3 task1 get A
Thread-3 task1 get B
Thread-4 task1 get A
Thread-4 task1 get B
Thread-5 task1 get A
Thread-5 task1 get B
Thread-6 task1 get A
Thread-6 task1 get B
Thread-7 task1 get A
Thread-7 task1 get B
Thread-8 task1 get A
Thread-8 task1 get B
Thread-9 task1 get A
Thread-9 task1 get B
Thread-10 task1 get A
Thread-10 task1 get B
Thread-1 task2 get B
Thread-1 task2 get A
Thread-2 task2 get B
Thread-2 task2 get A
Thread-4 task2 get B
Thread-4 task2 get A
Thread-3 task2 get B
Thread-3 task2 get A
Thread-5 task2 get B
Thread-5 task2 get A
Thread-6 task2 get B
Thread-6 task2 get A
……

浙公网安备 33010602011771号