Skip to main content
 首页 » 编程设计

Python多线程和不一致的输出

2025年05月04日35lonelyxmas

import threading 
 
x = 0; 
 
class Thread1(threading.Thread): 
    def run(self): 
        global x 
        for i in range(1,100000): 
            x = x + 1 
 
class Thread2(threading.Thread): 
    def run(self): 
        global x 
        for i in range(1,100000): 
            x = x - 1 
 
#create two threads 
t1 = Thread1() 
t2 = Thread2() 
 
#start the threads 
t1.start() 
t2.start() 
 
#wait for the threads to finish 
t1.join() 
t2.join() 
 
print x; 

多次运行会产生不同的输出,一些是负的,一些是正的。是不是因为两个线程使用的是同一个全局x?我不明白为什么:在一切尘埃落定之后,净效果(输出)不应该是一样的吗?

请您参考如下方法:

不一定。想象一下以下事件序列。我们将在程序运行一段时间后的某个精确时刻开始; Thread1 和 Thread2 都在它们的 for 循环中,并且 x = 0

  1. Thread1 拥有控制权。它访问 x 以确定 x + 1 的值; x 为 0,因此结果为 1。然而……
  2. 在 Thread1 完成分配之前,控制权传递给 Thread2。 x 仍然是 0。
  3. Thread2 现在访问 x。它计算 x - 1,即 -1,因为 x 仍然是 0。由于线程时间的不可预测性,它设法完成操作,将 -1 分配给 x。
  4. 控制现在返回到 Thread1。它已经计算出 x + 1 的值为 1。它将 1 分配给 x。

两个线程都完成了一次迭代,x的值应该是0,但它的实际值是1。