简体   繁体   English

在多线程中共享全局变量在python中不起作用

[英]share a global variable in multi threading doesn't work in python

I am trying to share a global variable between two function in python . 我正在尝试在python两个函数之间共享全局变量。 They are working at the same time whith multitreading. 他们正在同时进行多重踩踏。 the problem is that its like the global variable is not global at all here is my code: 问题是它就像全局变量根本不是全局变量,这是我的代码:

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()

The problem is that while nn only gets evaluated once. 问题是, while nn仅被评估一次。 When it is, it happens to be False because f1 has not yet made it True so f2 finishes running. 如果是,则恰好为False因为f1尚未将其设置为True因此f2完成运行。 If you initialize nn = True you'll see it is being accessed by both f1 and f2 如果您初始化nn = True ,将会看到f1f2都在访问它

Global variables work fine in python. 全局变量在python中工作正常。

The issue in your code would be that you first start f1 function , which goes into sleep for 0.5 seconds. 代码中的问题是您首先启动f1函数,该函数进入睡眠状态达0.5秒。

Then immediately after starting f1 , you also start f2 and then inside that you have the loop - while nn - but initial value of f2 is False, hence it never goes into the while loop , and that thread ends. 然后在启动f1之后立即启动f2 ,然后在其中启动循环while nn但f2的初始值为False,因此它永远不会进入while循环,并且该线程结束。

Are you really expecting the code to take more than 0.5 seconds to reach from start f1 thread and the while nn condition (so that nn can be set to True ) ? 您是否真的希望代码从启动f1线程和while nn条件开始需要花费超过0.5秒的while nn (以便nn可以设置为True )? I think it would not take more than few nano seconds for the program to reach there. 我认为程序到达那里不会花费超过几纳秒的时间。

Example of global variables working - 全局变量工作示例-

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM