Mat*_*hew 5 python variables multithreading loops multiprocessing
所以我有这个代码:
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()
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么我不能bar
给=
到true
.如果是这样,那么其他线程应该看到的变化,写Success!
Die*_*anz 11
bar
是一个全局变量.你应该放在global bar
里面example()
:
def example():
global bar
while True:
time.sleep(5)
bar = True
Run Code Online (Sandbox Code Playgroud)
global bar
内部的原因foo()
.global
语句,否则它将在函数内部完成.这就是为什么有必要把global bar
里面example()
小智 1
您必须将“bar”指定为全局变量。否则“bar”仅被视为局部变量。
def example():
global bar
while True:
time.sleep(5)
bar = True
Run Code Online (Sandbox Code Playgroud)