在Python函数中传递线程之间的变量[Beginner]

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)