首页 > 解决方案 > Python 线程在 PyGame 中的资产加载时崩溃

问题描述

我已经构建了一些代码来将资产加载到字符类中。这在单个线程中工作正常,但我希望在加载资产时有一个加载屏幕。

我把资产加载到一个函数中,并试图让它在一个单独的线程中运行。问题是它现在挂起,似乎甚至没有执行主线程。

我一直关注内存使用情况,并且内存表现良好(从 1976M 中永远不会超过 500M,位或字节我不确定,这是 PyCharm 报告的任何内容)。

import threading
import os
import pygame
from pygame.locals import *

def load_assets(screen: pygame.Surface, results: List):
    print("thread: started to load assets in thread")
    appearances1 = {} # some dictionary, Dict[str, Dict[str, str]]
    default_outfit = "office_wear"

    print("thread: instance of game class to be created")
    game = Game("lmao", screen) # crashes somewhere here when running multithreaded
    print("thread: game initialized") # this is never achieved
    # rest of function not relevant
    results.append(game)

def main():
    # ====== INITIALIZE PYGAME ======
    pygame.init()
    pygame.font.init()
    screen = pygame.display.set_mode((1024, 768))
    clock = pygame.time.Clock()

    loading = create_loading_screen(screen)
    loading.display(screen)
    pygame.display.flip()

    # ====== START OTHER THREAD FOR LOADING ASSETS ======
    results = []
    x = threading.Thread(
        target=load_assets, args=(screen, results), daemon=True
    )

    x.start()
    while x.is_alive():
        # never see this print statement!
        print("x is fine")  # want to blit loading screen here

    # if I comment out the threading, and run the following instead, my game boots up just fine
    # in under 3-4 seconds of waiting for the assets to load
    # load_assets(screen, results)

    game = results[0]
    
    # other code here to render the game, no more threading after this point
    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                return -1
        game.main()
        pygame.display.flip()
        clock.tick(game.fps)

if __name__ == '__main__':
    main()

你可以在这里看到打印语句(一切都挂起,我们甚至没有进入主线程!) 在此处输入图像描述

标签: pythonpygame

解决方案


我弄清楚了这个问题。我现在感觉真的很愚蠢......问题是我的游戏初始化程序正在触摸 pygame.display() 我已经知道它不应该......我需要小睡......


推荐阅读