2

Is it possible to observe the current value of a variable with a thread? Example: I have a variable which changes it's value every second and the function check(), which should print "over 10" as soon as the variable is over 10.

Any ideas ?

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)

1 Answer 1

1

The timer in your check() function is not the same variable as the top-level timer variable. The one in check() is a local.

Try changing check() like this:

def check ():
    global timer
    ...the rest is unchanged...

The global keyword allows the check() function to see the top-level timer.

Then, since check() no longer expects an argument, you can start it more simply:

threading.Thread(target= check, name= "TimerThread").start()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Everything is working as expected now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.