递归锁

一种情况,会造成死锁,,代码如下

import threading
import time

class MyThread(threading.Thread):

    def actionA(self):
        A.acquire()
        print(self.name,'gotA',time.ctime())
        time.sleep(2)

        B.acquire()
        print(self.name, 'gotB', time.ctime())
        time.sleep(1)

        B.release()
        A.release()

    def actionB(self):
        B.acquire()
        print(self.name, 'gotB', time.ctime())
        time.sleep(2)

        A.acquire()
        print(self.name, 'gotA', time.ctime())
        time.sleep(1)

        A.release()
        B.release()

    def run(self):
        self.actionA()
        self.actionB()





if __name__ == '__main__':

    A = threading.Lock()
    B = threading.Lock()


    L = []

    for i in range(5):
        t = MyThread()
        t.start()
        L.append(t)

    for i in L:
        i.join()

    print('ending-------')

 

 

 

用递归锁,可以避免死锁。代码如下

import threading
import time

class MyThread(threading.Thread):

    def actionA(self):
        r_lock.acquire()
        print(self.name,'gotA',time.ctime())
        time.sleep(2)

        r_lock.acquire()
        print(self.name, 'gotB', time.ctime())
        time.sleep(1)

        r_lock.release()
        r_lock.release()

    def actionB(self):
        r_lock.acquire()
        print(self.name, 'gotB', time.ctime())
        time.sleep(2)

        r_lock.acquire()
        print(self.name, 'gotA', time.ctime())
        time.sleep(1)

        r_lock.release()
        r_lock.release()

    def run(self):
        self.actionA()
        self.actionB()





if __name__ == '__main__':

 
    r_lock = threading.RLock()

    L = []

    for i in range(5):
        t = MyThread()
        t.start()
        L.append(t)

    for i in L:
        i.join()

    print('ending-------')

 

posted @ 2018-05-04 14:49  阜阳小全  阅读(120)  评论(0编辑  收藏  举报