使用多处理时,何时将主进程中的变量导入子进程?



我被告知,要将变量导入到多处理池中的子进程,您需要使用初始值设定项。

奇怪的是,我可以调用子进程的主循环中定义的变量,而无需使用初始值设定项:

import multiprocessing
import numpy as np
def ChildFun(i):
print(myValue)
print(f'Processing the index {i}')
if __name__ == "__main__":
myValue = 'This should not appear'
myList = np.arange(5)
with multiprocessing.Pool() as pool:
pool.map(ChildFun,myList)

通常,我希望只看到

Processing the index 2
Processing the index 0
Processing the index 3
Processing the index 1
Processing the index 4

但我得到

This should not appear
This should not appear
This should not appear
This should not appear
This should not appear
Processing the index 2
Processing the index 0
Processing the index 3
Processing the index 1
Processing the index 4

怎么来了?multiprocessing是否从主进程导入所有变量,即使它们受if __name__ == "__main__":保护? 还是它只是在子流程中找不到的主流程变量中搜索?

似乎是因为Unix处理分叉的方式,正如这里解释的那样:Python多处理--单独进程中的全局变量共享id?

我的猜测是,使用启动器更干净(你知道你传递了什么(,并且对于共享只读变量更明确。但大多数情况下,这可能是使您的代码在其他平台窗体(通常在Windows上(上工作的方法,这些平台窗体没有相同的分叉机制。

最新更新