You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中初始选择Yes后如何停止Timer线程?

Python 线程计时器停止功能修复方案

原代码问题分析

你的代码存在两个核心问题:

  1. 输入"yes"后调用x.join()会让主线程彻底阻塞,无法再接收后续用户输入,自然无法响应"no"指令
  2. 子线程的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:44:49