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