python 线程锁


python 互斥锁

from threading import Lock, Thread
from time import sleep

# 生成一把锁 mutex
= Lock() money = 100 def fn():
  # 这里涉及到全局数据共享, 需要开始加锁 mutex.acquire()
global money temp = money sleep(0.1) money = temp - 1 print(money)
  # 这里释放锁 mutex.release()
if __name__ == "__main__": thread_arr = [] for i in range(10): t = Thread(target=fn) t.start() thread_arr.append(t) for i in thread_arr: i.join() print(f"最终计算结果{money}")