I have download a game based on pygame:https://github.com/justinmeister/Mario-Level-1. Then I open multiple terminals, each terminal runs this game, to test whether it support multi-process. Everything is OK.
However, when I use multiprocessing lib to run this game, an error is raised
CXIO: fatal IO error 11 (Resource temporarily unavailable) on X server ":0"
after 155 requests (155 known processed) with 0 events remaining.
My code is like this:
processes = []
for rank in range(0, n):
p = mp.Process(target=main, args=())
p.start()
processes.append(p)
time.sleep(1)
processes[0].join()
Could anyone give me a hand? Any help will be great appreciated.
Multiprocessing and GUI do not mix. If you want to use multiprocessing, then isolate the multiprocessing part of your code from the GUI (PyGame) part, and make sure that the PyGame code doesn't run in one of the children, or that children don't start after you start using PyGame.
Or as a general rule, don't mix multiprocessing with PyGame.
Full Explanation
There are actually a bunch of layers to PyGame. Starting from the top layer,
With multiprocessing, your process will call
fork()
to copy itself. However, the copies are imperfect, and some pieces of code may not behave correctly after forking.In particular, LibXCB is written with the assumption that it owns the connection to the X11 server. After forking, this is no longer true. Both processes will share a connection to X11, and messages from the X11 server will only be recieved by one of the processes sharing the connection with X11.
Imagine that you're talking to someone with text messages, except some of your messages get sent to Alice, and the other messages get sent to Bob. Nobody told you that this is happening. The conversation wouldn't make any sense. That's what's happening here.
Solutions
Use
threading
instead ofmultiprocessing
Only use PyGame from one of the processes, and make sure that process doesn't fork.
Use the
forkserver
(orspawn
) start method withmultiprocessing
.Spawn completely different processes.