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

Python创建双线程实现输入询问与结果并行展示的代码问题排查

问题根因
  • 你的OutPut线程的run方法仅会执行1次:两个线程同时启动时,OutPut线程会第一时间判断当时的result值,此时用户还没完成输入、result还是None,判断不满足直接就退出了,自然不会打印后续输入的内容。
  • 缺少对全局变量result的读写保护,多线程同时读写同一个变量可能出现数据竞争问题。
  • 输出线程没有持续监听result变化的逻辑,也没有配套的退出判断条件。
修复后的完整代码
from threading import Thread, Lock

result = None
lock = Lock()
new_result = False  # 标记是否有未打印的新输入


class OutPut(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global result, new_result
        while True:
            with lock:
                # 检测到新输入就打印
                if new_result:
                    # 输入为0时退出线程
                    if result == 0:
                        break
                    print('Number entered was: {}'.format(result))
                    new_result = False


class Write(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global result, new_result
        while True:
            num = int(input('Enter a number? '))
            with lock:
                result = num
                new_result = True
            # 输入为0时退出线程
            if num == 0:
                break


threadIO = Write()
threadOutPut = OutPut()

arrThread = [threadIO, threadOutPut]

for tH in arrThread:
    tH.start()

for t in arrThread:
    t.join()

print('===== THREADS OFF =====')
改动说明
  • 给OutPut线程新增了循环逻辑,会持续监听输入内容的变化,直到用户输入0后同步退出
  • 新增了线程锁lock,保证全局变量的读写是原子操作,避免多线程数据错乱
  • 新增了new_result标记位,避免同一个输入的数字被重复打印多次

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:09:03