Python多线程:如何在首个线程结束后立即输出结果?
问题解决方法
核心问题分析
你的代码存在两个关键问题:
- 函数
some_func定义在线程启动之后,运行时会触发NameError(线程启动时找不到目标函数)。 - 终端输出缓冲会导致打印内容延迟显示,看起来像是两个结果同时输出。
修正后的代码
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
相关产品推荐
相关产品推荐

