死锁与递归锁

Posted 丫丫625202

tags:

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

死锁导致程序卡死,
互斥锁只能acquire一次,想acquire必须先release。

from threading import Thread,Lock
import time
mutexA=Lock()
mutexB=Lock()
class MyThread(Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        self.f1()
        self.f2()
    def f1(self):
        mutexA.acquire()
        print("%s mutex A" % self.name)
        time.sleep(1)
        mutexB.acquire()
        print("%s mutex B" % self.name)
        mutexA.release()
        mutexB.release()
    def f2(self):
        mutexB.acquire()
        print("%s mutex B" % self.name)
        time.sleep(1)
        mutexA.acquire()
        print("%s mutex A" % self.name)
        mutexA.release()
        mutexB.release()
if __name__ == "__main__":
    for i in range(10):
        t=MyThread()
        t.start()奥

递归锁,RLock,可以连续acquire()多次。RLock内部有一个计数器,每acquire()一次计数器加1,只要计数不为0就不能被其他线程抢到。

from threading import Thread,RLock
import time
mutexB=mutexA=RLock()
技术分享图片
class MyThread(Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        self.f1()
        self.f2()
    def f1(self):
        mutexA.acquire()
        print("%s mutex A" % self.name)
        time.sleep(1)
        mutexB.acquire()
        print("%s mutex B" % self.name)
        mutexA.release()
        mutexB.release()
    def f2(self):
        mutexB.acquire()
        print("%s mutex B" % self.name)
        time.sleep(1)
        mutexA.acquire()
        print("%s mutex A" % self.name)
        mutexA.release()
        mutexB.release()
if __name__ == "__main__":
    for i in range(10):
        t=MyThread()
        t.start()
View Code

 


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

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

死锁现象与递归锁

死锁与递归锁

10 并发编程-(线程)-GIL全局解释器锁&死锁与递归锁

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

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