Python中初始选择Yes后如何停止Timer线程?
Python 线程计时器停止功能修复方案
原代码问题分析
你的代码存在两个核心问题:
- 输入"yes"后调用
x.join()会让主线程彻底阻塞,无法再接收后续用户输入,自然无法响应"no"指令 - 子线程的
while True是无终止条件的死循环,主线程没有可靠方式通知它停止运行
修复后的代码
import threading import time def timer(stop_event): count = 0 # 用事件对象作为循环终止条件 while not stop_event.is_set(): time.sleep(1) count += 1 print("You have logged in for:", count, "seconds.") # 创建线程安全的停止事件 stop_event = threading.Event() x = threading.Thread(target=timer, args=(stop_event,), daemon=True) x.start() while True: solution = input("Would you like to continue the program:").strip().lower() if solution == "no": # 发送停止信号 stop_event.set() # 等待子线程正常结束 x.join() print("Timer stopped.") break elif solution == "yes": print("Timer is running, input 'no' to stop it.") else: print("Invalid request! Please input 'yes' or 'no'.")
关键修改说明
- 使用
threading.Event()实现线程间安全的信号传递,替代无终止的死循环 - 主线程改为持续循环接收用户输入,不再因
join()阻塞 - 当用户输入"no"时,通过
stop_event.set()通知子线程终止循环,再调用x.join()确保子线程正常退出 - 保留守护线程设置,作为极端情况下的兜底保障
内容的提问来源于stack exchange,提问作者Ultrascope Boy
相关产品推荐
相关产品推荐

