5.1.17 死锁与死锁的解决(递归锁)

Posted beallaliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5.1.17 死锁与死锁的解决(递归锁)相关的知识,希望对你有一定的参考价值。

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锁
卡住了。。。。。。
View Code

 

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()

 

以上是关于5.1.17 死锁与死锁的解决(递归锁)的主要内容,如果未能解决你的问题,请参考以下文章

死锁 与 递归锁

死锁现象与递归锁

python并发编程之多线程2------------死锁与递归锁,信号量等

python 并发编程 多线程 死锁现象与递归锁

死锁与递归锁

11.python并发入门(part4 死锁与递归锁)