pycharm 如何在Python中初始选择“是”后停止计时器线程?

nkoocmlb  于 2023-10-20  发布在  PyCharm
关注(0)|答案(1)|浏览(101)
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!")

我正在编写一个Python程序,在这个程序中我使用一个单独的线程实现了一个计时器。系统会提示用户选择是否要继续执行程序,最初,如果用户选择“是”,则计时器开始运行。然而,一旦我选择了“是”,我就不知道如何让程序在那之后对“否”做出响应。

8yparm6h

8yparm6h1#

全局作用域变量在所有从主程序启动的线程中都是可见的,因此您可以将其用作一种哨兵。
大概是这样的:

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')

另外,不要依赖计数器来计算运行时间。sleep()不精确

相关问题