作者hl4 (Minimi)
看板Python
标题[问题] variable scope in threads
时间Fri Jun 18 17:58:46 2010
我希望以计时的方时停止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
1F:推 ckclark:def a():底下也要写global stop 06/18 18:58
2F:推 hilorrk:原来python可以有nested function definition? 06/18 21:36
3F:推 ck574b027:nested意思感觉跟lambda很像。 07/10 12:45