【发布时间】:2020-05-28 19:33:21
【问题描述】:
import threading
COUNTER = 100000
lock = threading.Lock()
def add():
global x
with lock:
for i in range(COUNTER):
x += 1
def subtract():
global x
with lock:
for i in range(COUNTER):
x -= 1
x = 0
t0 = threading.Thread(target = add)
t1 = threading.Thread(target = subtract)
t0.start()
t1.start()
print(x)
# The output shall be zero isn't it?
我根据我在课程中看到的代码编写了这段代码,但实际上效果并不好。共享变量时,线程对数据的处理非常错误
【问题讨论】:
标签: python multithreading python-3.8 locks