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

Python主线程结束时如何停止子线程?含问题代码与报错

如何在主线程结束时优雅终止Python子线程?

首先,._stop()是Python线程模块的私有方法,绝对不应该直接调用——它不仅会引发报错,还可能导致线程资源泄漏、状态不一致等问题。正确的思路是通过优雅的方式让线程自行退出,针对你创建的两种子线程,分别提供解决方案:

一、处理无限循环任务的子线程

使用线程安全的终止标志(比如threading.Event)控制循环退出,这是Python中终止循环线程的标准做法:

import threading

# 定义线程可访问的终止标志
stop_event = threading.Event()

def run():
    while not stop_event.is_set():
        # 执行你的任务逻辑
        pass

thread = threading.Thread(target=run, daemon=True)
thread.start()

# 主线程结束前,设置终止标志让子线程主动退出
stop_event.set()
thread.join()  # 等待子线程完全执行完退出逻辑

二、处理Flask Web服务线程

Flask的app.run()是阻塞调用,无法直接中断,需要改用Werkzeug的服务器实例实现可控启停:

import threading
from werkzeug.serving import make_server

class FlaskServer:
    def __init__(self, app, host="0.0.0.0", port=port):
        self.server = make_server(host, port, app)
        self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)

    def start(self):
        Log.new_record(record_type="INFO", record_text=f"The webserver has been started. Server is running on port: {port}")
        self.thread.start()

    def stop(self):
        self.server.shutdown()
        self.thread.join()

# 初始化并启动Web服务线程
web_server = FlaskServer(app)
web_server.start()

# 主线程结束前,优雅停止Web服务
web_server.stop()

关于守护线程的补充说明

你已经将线程设置为daemon=True,这意味着主线程结束时,这些守护线程会被Python解释器强制终止。但这种强制终止是粗暴的,可能导致线程中的资源(比如文件句柄、网络连接)无法正常释放,因此优先推荐上面的优雅退出方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:02:20