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

Python多线程:如何在首个线程结束后立即输出结果?

问题解决方法

核心问题分析

你的代码存在两个关键问题:

  1. 函数some_func定义在线程启动之后,运行时会触发NameError(线程启动时找不到目标函数)。
  2. 终端输出缓冲会导致打印内容延迟显示,看起来像是两个结果同时输出。

修正后的代码

import threading
import queue
import time

def some_func(queue: queue.Queue, val: int):
    time.sleep(val*2 + 5)
    queue.put(val)

q = queue.Queue()
thread1 = threading.Thread(target=some_func, args=(q,0))
thread2 = threading.Thread(target=some_func, args=(q,1))

thread1.start()
thread2.start()

first_result = q.get()
print(first_result, flush=True)

second_result = q.get()
print(second_result, flush=True)

关键修改说明

  • 调整函数定义位置:将some_func移到线程创建代码之前,确保线程启动时能找到目标函数。
  • 强制刷新输出:在print语句中添加flush=True,避免终端缓冲延迟,让第一个线程的结果在完成后立即显示,第二个线程完成后再显示其结果。

内容的提问来源于stack exchange,提问作者Eloi Canals Pascual

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:20:23