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!
bar
is a global variable. You should put global bar
inside example()
:
def example():
global bar
while True:
time.sleep(5)
bar = True
global bar
inside foo()
.global
statement has been used. That's why it's necessary to put global bar
inside example()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With