zoukankan      html  css  js  c++  java
  • python Lock、RLock

    Lock: 只能acquire一次,下一次acquire必须release后才能,不然会造成死锁

    from threading import Lock
    
    total = 0
    lock = Lock()
    def add():
        #1. dosomething1
        #2. io操作
        # 1. dosomething3
        global lock
        global total
        for i in range(1000000):
            lock.acquire()
            total += 1
            lock.release()
    
    
    def desc():
        global total
        global lock
        for i in range(1000000):
            lock.acquire()
            total -= 1
            lock.release()
    
    import threading
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=desc)
    thread1.start()
    thread2.start()
    
    
    #
    thread1.join()
    thread2.join()
    print(total)

    RLock: 在同一个线程里面,可以连续调用多次acquire, 一定要注意acquire的次数要和release的次数相等

    from threading import  RLock
    total = 0
    lock = RLock()
    def add():
        #1. dosomething1
        #2. io操作
        # 1. dosomething3
        global lock
        global total
        for i in range(1000000):
            lock.acquire()
            lock.acquire()
            total += 1
            lock.release()
            lock.release()
    
    
    def desc():
        global total
        global lock
        for i in range(1000000):
            lock.acquire()
            total -= 1
            lock.release()
    
    import threading
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=desc)
    thread1.start()
    thread2.start()
    
    
    #
    thread1.join()
    thread2.join()
    print(total)
  • 相关阅读:
    redis 中 发布订阅 的 数据类型
    excelExport.js 导出 excel 表格
    Go 出现:err is shadowed during return(err在返回过程中被隐藏)
    Go 服务端 向 firebase Android 端 fcm 信息
    Python全栈day 03
    Python全栈day 01
    开发流程与版本管理规范
    php 魔术常量
    sql 消除重复
    重置mysql密码
  • 原文地址:https://www.cnblogs.com/callyblog/p/11142218.html
Copyright © 2011-2022 走看看