是否可以通过线程观察变量的当前值?例:我有一个变量,它每秒更改一次它的值,还有一个函数check(),一旦变量超过10,它应该立即显示“超过10”。
任何想法?
import threading
import time
def check (timer):
print("thread started")
while True:
if timer > 10:
print("over 10")
timer = 0
threading.Thread(target= check, name= "TimerThread", args=((timer,))).start()
while True:
print(str(timer))
timer = timer + 1
time.sleep(1)
timer
函数中的check()
与顶级timer
变量不同。 check()
中的一个是本地的。
尝试像这样更改check()
:
def check ():
global timer
...the rest is unchanged...
global
关键字允许check()
函数查看顶级timer
。
然后,您无需在启动线程时提供任何参数:
timer = 0
threading.Thread(target= check, name= "TimerThread").start()