如何观察线程变量?

问题描述 投票:0回答:1

是否可以通过线程观察变量的当前值?例:我有一个变量,它每秒更改一次它的值,还有一个函数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)
python-3.x multithreading observers
1个回答
0
投票

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()
© www.soinside.com 2019 - 2024. All rights reserved.