【问题标题】:Multithreaded Pygame多线程 Pygame
【发布时间】:2021-12-01 01:25:22
【问题描述】:

我正在尝试制作多线程 pygame 应用程序。 这是代码示例

import threading
import numpy as np
import time
import sys
import pygame

class Test:
    def __init__(self):
        pygame.init()
        self.surface = pygame.display.set_mode((400, 300))

    def do_smth(self):
        while True:
            time.sleep(2)
            print(np.random.randint(10, 20))

    def test(self):
        p = 10
        while True:

            self.surface.fill((255, 255, 255))
            pygame.draw.rect(self.surface, (255, 0, 0), (p, 10, 70, 65))

            event = pygame.event.poll()

            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                p += 10

            pygame.display.update()

如果我像这样测试它就可以了

T = Test()
T.test()

但是当我尝试使用线程执行此操作时 - 我收到错误 t = threading.Thread(target=T.test) t2 = threading.Thread(target=T.do_smth)

t.start()
t2.start()

t.join()
t2.join()

线程 Thread-1 中的异常: 回溯(最近一次通话最后): _bootstrap_inner 中的文件“/usr/lib/python3.8/threading.py”,第 932 行 自我运行() 运行中的文件“/usr/lib/python3.8/threading.py”,第 870 行 self._target(*self._args, **self._kwargs) 文件“”,第 34 行,在测试中 pygame.display.update() pygame.error: 无法使 GL 上下文当前

我该如何处理?

【问题讨论】:

  • 你真的需要 Pygame 的线程吗?我认为它会自动
  • 所有图形操作都应该在 pygame 中的单个线程中执行。如果您有耗时的游戏逻辑或外部database look-ups,那么这些可能会被卸载到单独的线程中。如果您的图形操作花费的时间太长,那么可能需要进行改进。

标签: python multithreading pygame


【解决方案1】:

根据SDL FAQ(Pygame 包装 SDL),您不能依赖可从多个线程访问的图形。您必须将所有绘图转移到主线程。您仍然可以让线程运行其他逻辑。

请注意,他们说的是“主线程”。通常使用锁是不够的。你可以例如设置一个包含作业的队列以在主线程上运行,并提供该队列,只要其中的作业可以在不同的线程中安全运行(例如,在他们需要知道要绘制什么的状态周围用锁保护) .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2011-02-27
    • 2022-06-14
    • 1970-01-01
    • 2021-06-04
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多