zoukankan      html  css  js  c++  java
  • 死锁现象与递归锁解法

    死锁:此时执行程序中两个或多个线程发生永久堵塞(等待),每个线程都在等待被其他线程占用并堵塞了的资源。

    递归锁:可以多次acquire加锁

        使用:from threading import RLock     mutexA=RLock()

    from threading import Thread,Lock
    import time
    
    mutexA=Lock()
    mutexB=Lock()
    
    
    
    class Mythead(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(2)
            mutexA.acquire()
            print('%s 抢到了A锁' %self.name)
            mutexA.release()
            mutexB.release()
    
    if __name__ == '__main__':
        for i in range(100):
            t=Mythead()
            t.start()
    
    结果:
    Thread-1 抢到A锁
    Thread-1 抢到B锁
    Thread-1 抢到了B锁
    Thread-2 抢到A锁
    后面就卡住了
    举例
    from threading import Thread,Lock,RLock
    import time
    
    mutexB=mutexA=RLock()
    
    
    class Mythead(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(2)
            mutexA.acquire()
            print('%s 抢到了A锁' %self.name)
            mutexA.release()
            mutexB.release()
    
    if __name__ == '__main__':
        for i in range(5):
            t=Mythead()
            t.start()
    
    结果:
    Thread-1 抢到A锁
    Thread-1 抢到B锁
    Thread-1 抢到了B锁
    Thread-1 抢到了A锁
    Thread-2 抢到A锁
    Thread-2 抢到B锁
    Thread-3 抢到A锁
    Thread-3 抢到B锁
    Thread-3 抢到了B锁
    Thread-3 抢到了A锁
    Thread-5 抢到A锁
    Thread-5 抢到B锁
    Thread-2 抢到了B锁
    Thread-2 抢到了A锁
    Thread-4 抢到A锁
    Thread-4 抢到B锁
    Thread-4 抢到了B锁
    Thread-4 抢到了A锁
    Thread-5 抢到了B锁
    Thread-5 抢到了A锁
    递归锁解法
  • 相关阅读:
    BZOJ3752 : Hack
    XIV Open Cup named after E.V. Pankratiev. GP of SPb
    XIII Open Cup named after E.V. Pankratiev. GP of Ukraine
    BZOJ2087 : [Poi2010]Sheep
    BZOJ2080 : [Poi2010]Railway
    BZOJ2082 : [Poi2010]Divine divisor
    Moscow Pre-Finals Workshop 2016. National Taiwan U Selection
    XIII Open Cup named after E.V. Pankratiev. GP of Asia and South Caucasus
    XIII Open Cup named after E.V. Pankratiev. GP of Azov Sea
    XIII Open Cup named after E.V. Pankratiev. GP of SPb
  • 原文地址:https://www.cnblogs.com/zhouhao123/p/11212142.html
Copyright © 2011-2022 走看看