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?我不明白为什么:所有的尘埃落定之后,净效应(输出)不应该相同吗?Python多线程和输出不一致
你的操作是不是原子。你应该使用锁来获得正确的结果。 – akaRem