为什么我用threading.Lock来锁定线程动作时,它的输出没有0呢?

问题描述 投票:0回答:1
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
1个回答
2
投票

更正后的代码是。

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的值。

© www.soinside.com 2019 - 2024. All rights reserved.