0

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()
2
  • 1
    What do you mean they are not global at all? Commented Jun 28, 2015 at 7:53
  • @AnandSKumar I meant that it seems to work localy but I found the problem. with answers, thanks Commented Jun 28, 2015 at 9:00

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, and not I tought it will be like: a-1,a-2,a-3...a-9,a-10,b-1,a-11,a-12,b-2...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.