Is it safe to use pygame in a thread or a process?

Viewed 304

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?

0 Answers
Related