在多线程中共享全局变量在 python 中不起作用
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 秒的时间(以便 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]
我试图在 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 秒的时间(以便 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]