5
所以我有這樣的代碼:在線程之間傳遞變量的變化在Python函數[新手]
import time
import threading
bar = False
def foo():
while True:
if bar == True:
print "Success!"
else:
print "Not yet!"
time.sleep(1)
def example():
while True:
time.sleep(5)
bar = True
t1 = threading.Thread(target=foo)
t1.start()
t2 = threading.Thread(target=example)
t2.start()
我試圖理解爲什麼我不能讓bar
到=
到true
。如果是這樣,那麼另一個線程應該看到更改並寫入Success!
這兩個函數中的'bar'不在同一個範圍內。在學習多線程之前,你應該處理範圍。無論如何,應該有可用於線程的互相資源構造。 – 2013-03-06 17:58:47
'time.sleep(1)'中的縮進是錯誤的。我認爲是打算在while循環中。 – 2013-03-06 18:21:27