5

So I have this code:

import time
import threading

bar = False

def foo():
    while True:
        if bar == True:
            print "Success!"
        else:
            print "Not yet!"
    time.sleep(1)

def example():
    while True:
        time.sleep(5)
        bar = True

t1 = threading.Thread(target=foo)
t1.start()

t2 = threading.Thread(target=example)
t2.start()

I'm trying to understand why I can't get bar to = to true.. If so, then the other thread should see the change and write Success!

2
  • The bar in the two functions are not in the same scope. You should deal with scopes before you learn multithreading. In any case there should be mutual-resource constructs you can use for threads. Commented Mar 6, 2013 at 17:58
  • Indentation in time.sleep(1) is wrong. I think is was intended to be inside the while loop. Commented Mar 6, 2013 at 18:21

2 Answers 2

11

bar is a global variable. You should put global bar inside example():

def example():
    global bar
    while True:
        time.sleep(5)
        bar = True
  • When reading a variable, it is first searched inside the function and if not found, outside. That's why it's not necessary to put global bar inside foo().
  • When a variable is assigned a value, it is done locally inside the function unless the global statement has been used. That's why it's necessary to put global bar inside example()
Sign up to request clarification or add additional context in comments.

Comments

1

You must specify 'bar' as global variable. Otherwise 'bar' is only considered as a local variable.

def example():
    global bar
    while True:
        time.sleep(5)
        bar = True

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.