Passing variable changes between threads in Python functions [Novice]

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 am trying to understand why I cannot get barup =to true. If so, then another thread should see the change and writeSuccess!

+5
source share
2 answers

baris a global variable. You should put global barinside 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 it is not found, then outside. Therefore, do not put it global barinside foo().
  • , , global. global bar example()
+11

"" . "bar" .

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

All Articles