简体   繁体   中英

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 . 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. When it is, it happens to be False because f1 has not yet made it True so f2 finishes running. If you initialize nn = True you'll see it is being accessed by both f1 and f2

Global variables work fine in python.

The issue in your code would be that you first start f1 function , which goes into sleep for 0.5 seconds.

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.

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 ) ? 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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