Discuss / Python / 为什么一直是零啊

为什么一直是零啊

Topic source

^_^

#1 Created at ... [Delete] [Delete and Lock User]

这段代码我循环多加了两个零执行了很多次,还一直输出的是0,不能理解是什么原因。。

import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(2000000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

^_^

#2 Created at ... [Delete] [Delete and Lock User]

环境:win11 , python 3.10.4

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

电脑速度太快你就把循环次数加10倍:

for i in range(20000000):

环境、版本一致、确实也一直都是0,试了很多遍了

画手

#5 Created at ... [Delete] [Delete and Lock User]

win11,python版本3.9.5,balance有时为0,有时不为0


  • 1

Reply