5

I need to use pygame in another thread, that is, the pygame loop and all the rendering on a seperate thread. I can't use pygame in the main thread.

I heard that some environments don't like that rendering is done outside of the main thread, but I couldn't find any confirmation or examples online.

So, is it safe to run pygame on a seperate thread? If not, is it safe to use pygame on a seperate process, instead? if not, what alternatives do I have?

Just to be clear, I want to do something like this:

from threading import Thread  # should I use multiprocessing.Process?

import pygame as pg


def run_game():
    pg.init()
    screen = pg.display.set_mode(...)
    running = True
    while running:
        # all pygame event handling and logic
        pg.dispaly.flip()


if __name__ == "__main__":
    t = Thread(target=run_game, args=())  # should be Process?
    t.start()
    # do other things on the main thread
    t.join()

On my machine (Windows 10, Python 3.7.9) this example works perfectly fine, and it also works with multiprocessing.Process instead of threading.Thread. I don't know if it will work on all platforms, and if a more complicated example would work on my machine.

So, is it safe, or do I need to do something different to make this work?

Shai Avr
  • 942
  • 8
  • 19
  • 1
    "I can't use pygame in the main thread" - Why? – Kingsley Sep 16 '20 at 05:46
  • 1
    You can use pygame in only one tread, but that thread is not necessarily the main thread – mousetail Sep 16 '20 at 09:15
  • @mousetail Can you show a confirmation for this? I heard that some environments don't like pygame outside of the main thread. – Shai Avr Sep 16 '20 at 19:13
  • You know it works on windows because you tested it there. In linux there is no real concept of a "main thread" since they are really all seperate processes that share a TGID. However, the POSIX standard does allow for different treatment of main and other threads so behavior might be different on Solaris or FreeBSD – mousetail Sep 16 '20 at 19:40
  • @mousetail Look [here](https://stackoverflow.com/questions/2970612/pygame-in-a-thread) for example. From what I see in this question, Pygame doesn’t play nice with threading, which is why I am looking for a confirmation or an example of correct usage of pygame with threading/multiprocessing. – Shai Avr Sep 18 '20 at 09:29
  • I can only confirm how the threading works for windows and linux. If your program should also work on mac, perhaps starting a process would be safer – mousetail Sep 18 '20 at 10:03

0 Answers0