在Python函数中的线程之间传递变量更改[初学者]
所以我有这个代码:在Python函数中的线程之间传递变量更改[初学者],python,multithreading,variables,loops,multiprocessing,Python,Multithreading,Variables,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)
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()
我正在试图理解为什么我不能将
条
设置为=
设置为真
。。如果是这样,那么另一个线程应该看到更改并写入成功代码>必须将“bar”指定为全局变量。否则,“bar”仅被视为局部变量
def example():
global bar
while True:
time.sleep(5)
bar = True
bar
是一个全局变量。您应该在示例()中放置全局条形图
:
- 读取变量时,首先在函数内部搜索,如果未找到,则在函数外部搜索。这就是为什么没有必要在
foo()中放入global bar
- 当一个变量被赋值时,除非使用了
global
语句,否则它是在函数内部本地完成的。这就是为什么有必要在example()中放入global bar
两个功能中的条不在同一范围内。在学习多线程之前,应该先处理作用域。在任何情况下,都应该有可用于线程的共同资源构造。time.sleep(1)
中的缩进是错误的。我想这是为了进入while循环。
def example():
global bar
while True:
time.sleep(5)
bar = True