微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 线程在 PyGame 中的资产加载时崩溃

如何解决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,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()

你可以在这里看到打印语句(一切都挂了,我们甚至没有进入主线程!)

enter image description here

解决方法

我发现了这个问题。我现在觉得真的很愚蠢...问题是我的游戏初始化器正在接触 pygame.display() 我已经知道它不应该...我需要小睡...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。