其他分享
首页 > 其他分享> > 死锁与递归锁

死锁与递归锁

作者:互联网

递归锁

一个线程拿到锁,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()

 

标签:__,name,递归,self,acquire,死锁,mutexA,mutexB
来源: https://www.cnblogs.com/zhengyiqun1992/p/10409059.html