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

如何在Python游戏中添加独立线程避免API调用导致卡顿

解决游戏API调用卡顿问题

你的问题核心是阻塞式API请求占用了游戏主线程,导致游戏循环暂停等待响应。用独立线程异步处理API请求就能解决这个问题,以下是两种简单可行的实现方式:

方法一:直接用threading创建单次线程

  1. 先在main.py开头导入线程模块:
import threading
import requests
  1. 保留你原来的sayThis函数,修改游戏主循环中的调用逻辑,把API请求放到子线程中执行:
while contGame: #a flag to continue the game 
   if (#你的击中条件):
       # 启动守护线程执行API调用,不阻塞主线程
       threading.Thread(
           target=sayThis,
           args=("http://localhost:54300/apistomach/say?text=great&blocking=true",),
           daemon=True
       ).start()
  • daemon=True设置为守护线程,确保游戏主线程结束时,子线程会自动退出,避免残留后台线程。

方法二:用线程池控制并发(适合高频触发场景)

如果玩家可能短时间内多次击中球,用线程池可以限制同时运行的线程数量,避免资源浪费:

  1. 导入线程池模块:
from concurrent.futures import ThreadPoolExecutor
import requests
  1. 在main.py开头初始化线程池:
# 最多同时运行2个线程,可根据需求调整
executor = ThreadPoolExecutor(max_workers=2)
  1. 主循环中提交任务到线程池:
while contGame: #a flag to continue the game 
   if (#你的击中条件):
       executor.submit(
           sayThis,
           "http://localhost:54300/apistomach/say?text=great&blocking=true"
       )

额外优化建议

  • 你的sayThis函数中except捕获了所有异常,建议改为捕获具体的请求异常,方便精准排查问题:
def sayThis(param):   
    try:
       api_url = param
       response = requests.post(api_url)
       response.json()
    except requests.exceptions.RequestException:
       print("service error occurred! check API connection ")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:03:24