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

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

    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-------')
  • 相关阅读:
    Liunx cal
    Liunx read
    IOS
    IOS
    ARPSpoofing教程(四)
    ARPSpoofing教程(三)
    ARPSpoofing教程(二)
    数据结构与算法分析
    hdu 2034
    hdu 2042
  • 原文地址:https://www.cnblogs.com/lhqlhq/p/8990594.html
Copyright © 2011-2022 走看看