在Python函数中在线程之间传递变量变化[初学者]

5 投票
2 回答
11984 浏览
提问于 2025-04-17 18:09

我有这段代码:

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 设为 true。如果能这样做,其他线程就应该能看到这个变化,并输出 Success!

2 个回答

1

你必须把'bar'声明为全局变量。否则,'bar'只会被当作局部变量来处理。

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

bar 是一个全局变量。你应该在 example() 函数里面加上 global bar

def example():
    global bar
    while True:
        time.sleep(5)
        bar = True
  • 当你要读取一个变量时,程序会先在函数内部找,如果找不到,再去外面找。所以在 foo() 里面不需要加 global bar
  • 当你要给一个变量赋值时,默认是在函数内部进行,除非你用了 global 这个声明。所以在 example() 里面就必须加 global bar

撰写回答