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-------')
  • 相关阅读:
    高阶函数与匿名函数
    A task in a suit and a tie:paraphrase generation with semantic augmentation解读
    利用tensorboard将数据可视化(tf1.x 和 tf2.x)
    IplImage, CvMat, Mat 的关系
    剑指OFFER之合并两个排序的链表
    整数与字符串的互相转化
    二分查找法
    集成算法
    003-决策树案例
    002-决策树构造实例
  • 原文地址:https://www.cnblogs.com/lhqlhq/p/8990594.html
Copyright © 2011-2022 走看看