简体   繁体   English

进程如何在python中获取全局变量的当前值?

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

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.但是,即使我按下“A”,“q”的值也总是 [0, 0, ……, 0]。“keyboard_process.join()”总是什么都不做。所以游戏不起作用。

How can a process get the current value of a global variable in python?进程如何在python中获取全局变量的当前值? Please help me.请帮我。

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.在@humble_D 的答案被删除之前,它有一个很好的链接到一个相关的答案,详细说明了一些进程间通信的方法。 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.老实说,如果您认真考虑将 PyGame 用于新游戏,它可能不需要多处理。 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 (eg: C/C++/Rust ) and launch that as the sub-process.如果需要发生一些超级 CPU 绑定的子进程,您可能最好用本地二进制编译语言(例如: C/C++/Rust )编写这部分并将其作为子进程启动。

But first, just write your game, then optimise the parts that are slow.但首先,只需编写您的游戏,然后优化缓慢的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM