如何用线程观察变量?
How to observe a variable with a thread?
是否可以用线程观察变量的当前值?
例子:
我有一个每秒更改其值的变量和函数 check(),一旦变量超过 10,它应该打印 "over 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)
check()
函数中的 timer
与顶级 timer
变量不是同一个变量。 check()
中的那个是本地的。
尝试像这样更改 check()
:
def check ():
global timer
...the rest is unchanged...
global
关键字允许 check()
函数查看顶级 timer
。
然后,由于 check()
不再需要参数,您可以更简单地开始它:
threading.Thread(target= check, name= "TimerThread").start()
是否可以用线程观察变量的当前值? 例子: 我有一个每秒更改其值的变量和函数 check(),一旦变量超过 10,它应该打印 "over 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)
check()
函数中的 timer
与顶级 timer
变量不是同一个变量。 check()
中的那个是本地的。
尝试像这样更改 check()
:
def check ():
global timer
...the rest is unchanged...
global
关键字允许 check()
函数查看顶级 timer
。
然后,由于 check()
不再需要参数,您可以更简单地开始它:
threading.Thread(target= check, name= "TimerThread").start()