[問題] variable scope in threads
我希望以計時的方時停止main中的while loop,於是我這樣寫:
stop = 0
def ab():
global stop
time.sleep(5)
stop=1
if __name__=="__main__":
x = threading.Thread(target = ab, args=())
x.start()
while 1:
print str(stop)
time.sleep(1)
if stop == 1:
break
運作相當正確。
但是,當我包成一個function的時候,就停不下來了,如下:
def a():
stop = 0
def ab():
global stop #刪除這一行也是失敗
time.sleep(5)
stop=1
x = threading.Thread(target = ab, args=())
x.start()
while 1:
print str(stop)
time.sleep(1)
if stop == 1:
break
if __name__=="__main__":
a()
threads只會共用最上層的變數嗎?
在不用global variable的情況下,有什麼方法可以達到相同的目標呢?
謝謝。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.87.144.205
推
06/18 18:58, , 1F
06/18 18:58, 1F
推
06/18 21:36, , 2F
06/18 21:36, 2F
推
07/10 12:45, , 3F
07/10 12:45, 3F
Python 近期熱門文章
PTT數位生活區 即時熱門文章