zoukankan      html  css  js  c++  java
  • python 多线程-01 锁

    import threading
    
    # lock = threading.RLock()
    
    # RLock 递归锁
    lock = threading.RLock()  
    Counter = [0]
    
    
    def add(C):
        lock.acquire()
        C[0] = C[0] + 1
        lock.release()
    
    
    if __name__ == '__main__':
        count = 0
        threads = []
        for i in range(10):
            t = threading.Thread(target=add, args=[Counter])
            threads.append(t)
    
        for t in threads:
            t.start()
            t.join()
    
        print(Counter)
    
    import threading
    
    lock = threading.Condition()
    
    Counter = [0]
    
    
    def add(C):
        lock.acquire()
        lock.wait()  
    
        C[0] = C[0] + 1
        print(C[0])
        lock.release()
    
    
    if __name__ == '__main__':
        threads = []
        for i in range(10):
            t = threading.Thread(target=add, args=[Counter])
            threads.append(t)
    
        for t in threads:
            t.start()
    
        while True:
            inp = int(input("
    >>>"))
            lock.acquire()
            lock.notify(inp)
            lock.release()
    
    import threading
    
    lock = threading.Event()
    
    Counter = [0]
    
    
    def add(C):
        lock.wait()
    
        C[0] = C[0] + 1
        print(C[0])
    
    
    if __name__ == '__main__':
        threads = []
        for i in range(10):
            t = threading.Thread(target=add, args=[Counter])
            threads.append(t)
    
        for t in threads:
            t.start()
    
        inp = int(input("
    >>>"))
        # 解锁
        lock.set()
    
        # 加锁
        lock.clear()
        inp = int(input("
    >>>"))
        # 解锁
        lock.set()
    
        threads = []
        for i in range(10):
            t = threading.Thread(target=add, args=[Counter])
            threads.append(t)
    
        for t in threads:
            t.start()
    
    
  • 相关阅读:
    找水王续
    找水王续
    本周学习进度
    Node.js 学习
    在Linux机器上安装MySQL
    ZStack串口通信
    Java编写串口程序
    ServerSocket
    ZigBee毕设
    ZigBee相关网站链接
  • 原文地址:https://www.cnblogs.com/pythonPath/p/12448742.html
Copyright © 2011-2022 走看看