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-------')
  • 相关阅读:
    2019年9月15日晚间测试-T1
    机房巨佬的随机名称生成器
    初来乍到
    GKurumi记
    GKurumi记
    小P的团战
    什么才算是真正的编程能力?
    java冒泡排序和快速排序
    “转行做程序员”很难?这里有4个重要建议
    Linux文件I/O(一)
  • 原文地址:https://www.cnblogs.com/lhqlhq/p/8990594.html
Copyright © 2011-2022 走看看