How can a process get the current value of a global variable in python?

Viewed 60

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.

1 Answers

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.

Related