[問題] variable scope in threads

看板Python作者 (Minimi)時間15年前 (2010/06/18 17:58), 編輯推噓3(300)
留言3則, 3人參與, 最新討論串1/1
我希望以計時的方時停止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
def a():底下也要寫global stop
06/18 18:58, 1F

06/18 21:36, , 2F
原來python可以有nested function definition?
06/18 21:36, 2F

07/10 12:45, , 3F
nested意思感覺跟lambda很像。
07/10 12:45, 3F
文章代碼(AID): #1C6qDUy9 (Python)
文章代碼(AID): #1C6qDUy9 (Python)