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

Python Thread未启动问题:跟随教程编写代码无输出

问题解决:Python多线程未输出计数器内容

你的代码逻辑本身是正确的,导致线程无输出的原因大概率是输出缓冲未及时刷新,或者全局变量的线程可见性问题,以下是两种可行的修复方案:

方案一:强制刷新输出缓冲区

在print语句中添加flush=True参数,强制终端立刻输出内容(默认情况下标准输出是行缓冲,子线程的输出可能被暂存而未显示):

import threading
import time

done = False

def worker():
    counter = 0
    while not done:
        time.sleep(1)
        counter += 1
        print(counter, flush=True)  # 添加flush=True

threading.Thread(target=worker).start()

input("Enter to quit")
done = True

方案二:使用threading.Event实现可靠的线程通信

全局变量的线程可见性偶尔会因为Python解释器的优化出现异常,用threading.Event作为线程间的信号量是更稳妥的方式:

import threading
import time

done = threading.Event()

def worker():
    counter = 0
    while not done.is_set():
        time.sleep(1)
        counter += 1
        print(counter, flush=True)

threading.Thread(target=worker).start()

input("Enter to quit")
done.set()  # 设置事件,通知子线程退出循环

直接调用worker函数能正常输出,是因为单线程模式下print的输出会被即时刷新,而多线程模式下子线程的输出缓冲未被触发,导致你看不到计数器内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:35:09