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?
我根据在课程中看到的一段代码做了这段代码,其实还没有那么好用。在共享变量的时候,线程对数据的操作很不正常
更正后的代码是。
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()
# Added the below lines
t0.join()
t1.join()
# END
print(x)
错误的原因是你的主线程没有等待你的子线程完成它们的进程. 这就是为什么你会得到不寻常的输出,因为你在中间打印x的值。