# 模拟银行存钱,初始金额0,执行十次,每次存1元
from threading import Thread,Lock
from time import sleep
bank = {
'zhangsan':0
}
bank_lock = Lock()
# 定义一个函数,作为新线程执行的入口函数
def posit(threadinx,amount):
# 操作共享数据时,申请获取锁
bank_lock.acquire()
print(f'{threadinx}申请了锁')
balance = bank['zhangsan']
sleep(0.2)
bank['zhangsan'] = balance + amount
print(f'子线程{threadinx}结束,当前余额为{bank["zhangsan"]}')
# 操作完共享数据后,释放锁
bank_lock.release()
# 存储线程对象
thread_list = []
for idx in range(1,11):
thread = Thread(target = posit, args=(idx, 1))
thread.start()
thread_list.append(thread)
for thread in thread_list:
thread.join()
print(f"主线程结束,最终余额为{bank['zhangsan']}")