recursive lock

In one case, it will cause deadlock, the code is as follows

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-------')

 

 

 

With recursive locks, deadlocks can be avoided. code show as below

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-------')

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325268465&siteId=291194637