码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-06-16 23:34:53      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:isp   %s   name   art   tar   closed   TE   main   class   

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 死锁与死锁的解决(递归锁)

标签:isp   %s   name   art   tar   closed   TE   main   class   

原文地址:https://www.cnblogs.com/beallaliu/p/9191694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!