Python 3.10.8 macOS 跑没有加锁的实例,发现也就是0,即使我增加了10倍的循环依旧是0,谁能给解释下呢?
但是我跑下面的demo却很容易就复现了不加锁后共享变量被污染的情况
import threading import time import Account # 定义一个函数来模拟取钱操作 def draw(account, draw_amount): # 账户余额大于取钱数目 if account.balance >= draw_amount: # 吐出钞票 print(threading.current_thread().name\ + "取钱成功!吐出钞票:" + str(draw_amount)) # time.sleep(0.001) # 修改余额 account.balance -= draw_amount print("\t余额为: " + str(account.balance)) else: print(threading.current_thread().name\ + "取钱失败!余额不足!") # 创建一个账户 acct = Account.Account("1234567" , 1000) # 模拟两个线程对同一个账户取钱 threading.Thread(name='甲', target=draw , args=(acct , 800)).start() threading.Thread(name='乙', target=draw , args=(acct , 800)).start()
因为python多线程是假的,一次只有一个线程能被执行,相当于有锁。
https://stackoverflow.com/questions/69993959/python-threads-difference-for-3-10-and-others
参考回答
Sign in to make a reply
炸毛钱钱菌
Python 3.10.8 macOS 跑没有加锁的实例,发现也就是0,即使我增加了10倍的循环依旧是0,谁能给解释下呢?
但是我跑下面的demo却很容易就复现了不加锁后共享变量被污染的情况