🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ import threading g_number = 0 # 创建一把全局互斥锁 g_lock = threading.Lock() def w1(): global g_number for i in range(1000000): # 尝试获取并且加锁 如果没有被锁定 就可以被我锁定;  # 如果已经被锁定 阻塞等待 直到成功获取并且锁定  g_lock.acquire() g_number += 1 # 释放锁资源 解锁  未锁定 ----> 未锁定状态 g_lock.release() def w2(): global g_number for i in range(1000000): g_lock.acquire() g_number += 1 g_lock.release() if __name__ == '__main__': t1 = threading.Thread(target=w1) t2 = threading.Thread(target=w2) t1.start() t2.start() t1.join() t2.join() print("g_number=", g_number) ~~~