How to Stop a Timer Thread After Initially Choosing "Yes" in Python?

32 Views Asked by At
import threading
import time

def timer():
    count = 0
    while True:
        time.sleep(1)
        count += 1
        print("You have logged in for:", count, "seconds.")

x = threading.Thread(target=timer, daemon=True)
x.start()

solution = input("Would you like to continue the program:")

if solution == "no":
    pass
elif solution == "yes":
    x.join()
else:
    print("Invalid request!")

I'm working on a Python program where I've implemented a timer using a separate thread. The user is prompted to choose whether they want to continue the program or not, and initially, if they choose "yes," the timer starts running. However, once I've chosen "yes," I can't figure out how to make the program respond to "no" after that.

1

There are 1 best solutions below

1
SIGHUP On BEST ANSWER

Global scoped variables are visible in all threads initiated from the main program so you can utilise that as a kind of sentinel.

Something like this:

import threading
import time

RUN = True

def timer():
    start = time.time()
    while RUN:
        time.sleep(1)
        print("You have logged in for:", int(time.time()-start), "seconds.")

(x := threading.Thread(target=timer)).start()

while True:
    solution = input("Would you like to continue the program:")

    if solution == 'yes':
        RUN = False
        x.join()
        break
    elif solution == 'no':
        pass
    else:
        print('Invalid request')

Also, don't rely on a counter for calculating the elapsed time. sleep() isn't precise