[英]share a global variable in multi threading doesn't work in python
我正在尝试在python
两个函数之间共享全局变量。 他们正在同时进行多重踩踏。 问题是它就像全局变量根本不是全局变量,这是我的代码:
import threading as T
import time
nn = False
def f1(inp):
global nn
while True:
inp=inp+1
time.sleep(0.5)
print 'a-'+str(inp)+"\n"
if inp > 10:
nn=True
print nn
def f2(inp):
inp=int(inp)
while nn:
inp=inp+1
time.sleep(1)
print 'b-'+str(inp)+"\n"
t1= T.Thread(target=f1, args = (1,))
t1.daemon = True
t1.start()
t2= T.Thread(target=f2, args = (1,))
t2.daemon = True
t2.start()
问题是, while nn
仅被评估一次。 如果是,则恰好为False
因为f1尚未将其设置为True
因此f2
完成运行。 如果您初始化nn = True
,将会看到f1
和f2
都在访问它
全局变量在python中工作正常。
代码中的问题是您首先启动f1
函数,该函数进入睡眠状态达0.5秒。
然后在启动f1之后立即启动f2
,然后在其中启动循环while nn
但f2的初始值为False,因此它永远不会进入while循环,并且该线程结束。
您是否真的希望代码从启动f1
线程和while nn
条件开始需要花费超过0.5秒的while nn
(以便nn可以设置为True
)? 我认为程序到达那里不会花费超过几纳秒的时间。
全局变量工作示例-
>>> import threading
>>> import time
>>> def func():
... global l
... i = 0
... while i < 15:
... l.append(i)
... i += 1
... time.sleep(1)
>>> def foo(t):
... t.start()
... i = 20
... while i > 0:
... print(l)
... i -= 1
... time.sleep(0.5)
>>> l = []
>>> t = threading.Thread(target=func)
>>> foo(t)
[0]
[0]
[0]
[0, 1]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.