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

在Pygame中使用multiprocessing时触发RuntimeError问题求助

问题解决:multiprocessing与Pygame的RuntimeError修复

错误根源

Windows系统中multiprocessing默认用spawn方式创建子进程,这种方式会重新导入主模块。如果直接在模块顶层写进程启动代码,子进程会重复执行这些代码,导致无限递归创建进程,触发RuntimeError。必须把进程启动逻辑放在if __name__ == '__main__':代码块内,保证只有主进程执行这部分代码。

修复后的完整代码

from csv import reader
import pygame
from sys import exit
import multiprocessing

def check():
    # pygame必须初始化并创建窗口才能处理事件
    pygame.init()
    pygame.display.set_mode((1, 1))  # 创建最小化隐藏窗口
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

def startgame():
    # 这里是你的play函数实现(根据实际逻辑调整)
    def play(command):
        print(f"执行命令: {command}")
        # 游戏核心逻辑写在这里
    
    while True:
        cmd = input("Present Command\n")
        play(cmd)

if __name__ == '__main__':
    # 仅主进程执行进程启动逻辑
    play_game_process = multiprocessing.Process(target=startgame)
    play_game_process.start()

    check_process = multiprocessing.Process(target=check)
    check_process.start()

    # 可选:等待子进程结束,防止主进程提前退出
    play_game_process.join()
    check_process.join()

关键说明

  • check函数必须初始化pygame并创建窗口,否则pygame事件系统无法正常捕获QUIT事件。
  • 文本输入进程和pygame事件进程相互独立,需确保两者逻辑不会互相阻塞。
  • 如果后续要打包成可执行文件,需要在if __name__ == '__main__':块开头添加multiprocessing.freeze_support()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:10:28