2

My code is like this:

import pygame
from multiprocessing import Process, Queue

#dosomething
#dosomething

def keyboard():
    keys_pressed = q.get()
    if key_pressed[pygame.K_a]:
        #dosomething

q = Queue()
keyboard_process = Process(target=keyboard)
keyboard_process.start()
while True:
    q.put(pygame.key.get_pressed())
    #dosomething
    keyboard_process.join()
    #dosomething

But, the value of "q" is always [0, 0, ……, 0] even if I press "A"."keyboard_process.join()" always does nothing.So the game doesn't work.

How can a process get the current value of a global variable in python? Please help me.

QWERTY_52_38
  • 58
  • 1
  • 5
  • 1
    Related https://stackoverflow.com/a/63649298/13782669 – alex_noname Nov 19 '20 at 13:30
  • you didn't actually pass the Queue to the subprocess, change the invocation to `Process(target=keyboard, args=(q, ))` and of course `def keyboard(q):` – Nullman Nov 19 '20 at 13:32
  • @Nullman but that's no use. – QWERTY_52_38 Nov 19 '20 at 13:54
  • 1
    @QWERTY_52_38 I would suggest not using processes or threads with pygame, unless you know about all the limitations SDL2 has regarding them. For your case, there's really no need at all to start a new process. It'll make the game slower, harder to debug, harder to reason about and more prone to bugs. And as you've noticed, you'll run into hard to solve problem like the problem in your question. Just use an event loop and process the events in your game loop. – Ted Klein Bergman Nov 19 '20 at 14:30

1 Answers1

2

The short answer is: "No".

When you start a separate child process, it gets a complete copy of the memory-space of the parent. Once started it is completely independent of the parent. The only way of communicating parent/child is to use some kind of inter-process communication mechanism - pipes, shared memory, network-sockets, files, etc.

However if you start a separate processing thread, all threads share the same memory.

Before @humble_D 's answer was deleted, it had a great link to a relevant answer detailing some methods of inter-process communication. Ref: multiprocessing: sharing a large read-only object between processes?

To be honest, if you're seriously considering PyGame for a new game, it probably doesn't need multiprocessing. If there's some super CPU-bound sub-process that needs to happen, you would probably be better off writing this part in a native-binary compiled language (e.g.: C/C++/Rust ) and launch that as the sub-process.

But first, just write your game, then optimise the parts that are slow.

Kingsley
  • 14,398
  • 5
  • 31
  • 53