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

Python如何停止在循环内部调用且定时递归触发的线程

问题原因分析
  • PRINT #1仅打印一次:anotherFunction1()是端口监听阻塞方法,无新客户端连接时会一直阻塞,不会执行后续的打印逻辑。
  • 程序无法退出的核心原因:
    1. Python主进程会等待所有非守护线程执行完成后才退出,你每次调用threading.Timer启动的都是默认非守护线程,sys.exit()仅作用于调用它的当前线程,无法终止其他存活线程。
    2. 主线程中的while True循环完全没有退出判断,子线程的终止操作无法影响主线程的运行逻辑。
可行解决方案

使用threading.Event()作为全局退出标志,配合守护线程实现全链路退出,修改后的代码如下:

import threading
import sys

# 全局退出事件
exit_event = threading.Event()

def parentFunction():
    # Other code
    while not exit_event.is_set():
        # 可给anotherFunction1添加超时参数,避免长时间阻塞无法及时检查退出标志
        var1, var2 = anotherFunction1()
        threading.Thread(target = anotherFunction2, args=(var1, var2), daemon=True).start()
        childFunction(var1,var2)
        print("PRINT #1: Running in Parent Function")

def childFunction(var1, var2):
    # 先判断是否要退出,避免触发新的定时器
    if exit_event.is_set():
        return
    # 启动定时器时设为守护线程
    threading.Timer(10, childFunction, args=(var1,var2), daemon=True).start()
    print("PRINT #2: Running in child function")
    
    # Other code 

    if (someConditionIsMet):
        print("PRINT #3: Exiting") 
        # 触发全局退出事件
        exit_event.set()
        # 若需立即终止整个进程,可直接调用os._exit(0),无需等待线程回收
        # import os
        # os._exit(0)
方案说明
  • 所有新开的Thread和Timer都设置daemon=True,主线程退出时会自动销毁所有守护线程,不会出现子线程残留导致进程挂起的问题。
  • 全局exit_event触发后,主线程的循环会在下一次检测时终止,同时childFunction也不会再启动新的定时器,所有线程链路都会逐步停止。
  • 如果逻辑中用到Threading.Lock,只需确保退出前正常释放锁即可,和退出逻辑本身无冲突。

内容的提问来源于stack exchange,提问作者codingray

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:06:04