简体   繁体   English

子进程未在 Windows 上继承 Python 全局变量

[英]Child process not inheriting Python global variable on Windows

I know that child processes won't see changes made after a fork/spawn, and Windows processes don't inherit globals not using shared memory.我知道子进程在 fork/spawn 之后不会看到所做的更改,并且 Windows 进程不会继承不使用共享内存的全局变量。 But what I have is a situation where the children can't see changes to a global variable in shared memory made before the fork/spawn.但是我遇到的情况是,孩子们无法看到在 fork/spawn 之前对共享内存中的全局变量所做的更改。

Simple demonstration:简单演示:

from multiprocessing import Process, Value
global foo
foo = Value('i',1)
def printfoo():
  global foo 
  with foo.get_lock():
    print(foo.value)
if __name__ == '__main__':
  with foo.get_lock():
    foo.value = 2
  Process(target=printfoo).start()

On Linux and MacOS, this displays the expected 2. On Windows, it displays 1, even though the modification to the global Value is made before the call to Process .在 Linux 和 MacOS 上,这显示预期的 2。在 Windows 上,它显示 1,即使对全局值的修改是在调用Process之前进行的。 How can I make the change visible to the child process on Windows, too?如何使 Windows 上的子进程也可以看到更改?

The problem here is that your child process creates a new shared value, rather than using the one the parent created.这里的问题是您的子进程创建了一个新的共享值,而不是使用父进程创建的共享值。 Your parent process needs to explicitly send the Value to the child, for example, as an argument to the target function:您的父进程需要显式地将Value发送给子进程,例如,作为目标函数的参数:

from multiprocessing import Process, Value

def use_shared_value(val):
    val.value = 2

if __name__ == '__main__':
    val = Value('i', 1)
    p = Process(target=use_shared_value, args=(val,))
    p.start()
    p.join()
    print(val.value)

(Unfortunately, I don't have a Windows Python install to test this on.) (不幸的是,我没有安装 Windows Python 来测试这个。)


Child processes cannot inherit globals on Windows, regardless of whether those globals are initialized to multiprocessing.Value instances. Windows 上的子进程不能继承全局变量,无论这些全局变量是否被初始化为multiprocessing.Value实例。 multiprocessing.Value does not change the fact that the child re-executes your file, and re-executing the Value construction doesn't use the shared resources the parent allocated. multiprocessing.Value不会改变子级重新执行您的文件的事实,并且重新执行Value构造不会使用父级分配的共享资源。

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

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