zoukankan      html  css  js  c++  java
  • 死锁与递归锁

    递归锁

    一个线程拿到锁,counter加1,该线程内又碰到加锁的情况,则counter继续加1,这期间所有其他线程都只能等待,等待该线程释放所有锁,即counter递减到0为止

    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(1)
            mutexA.acquire()
            print('%s 拿到A锁' % self.name)
            mutexA.release()
            mutexB.release()
    
    
    if __name__ == '__main__':
        for i in range(3):
            t = Mythread()
            t.start()

    死锁

    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(1)
            mutexA.acquire()
            print('%s 拿到A锁' % self.name)
            mutexA.release()
            mutexB.release()
    
    
    if __name__ == '__main__':
        for i in range(3):
            t = Mythread()
            t.start()
  • 相关阅读:
    POJ 2057 The Lost House
    SRM 597
    poj3020(Antenna Placement)
    poj3041(Asteroids)
    poj2388(Who's in the Middle)
    poj3687(Labeling Balls)
    poj1094(Sorting It All Out)
    poj3026(Borg Maze)
    poj1258(Agri-net)
    poj2485(Highways)
  • 原文地址:https://www.cnblogs.com/zhengyiqun1992/p/10409059.html
Copyright © 2011-2022 走看看