gpt4 book ai didi

具有大共享数据的 Python 多处理

转载 作者:行者123 更新时间:2023-12-01 08:33:27 24 4
gpt4 key购买 nike

我正在使用 python 开发一个应用程序来使用 mutliprocessing 模块处理数据,代码如下所示:

import multiprocessing

globalData = loadData() #very large data

def f(v):
global globalData
return someOperation(globalData,v)

if __name__ == '__main__':
pool = multiprocessing.Pool()
arr = loadArray() #some big list
res = pool.map(f,arr)

问题是所有子进程都需要相同的全局数据来处理该函数,因此加载它并需要很长时间,在所有子进程之间共享此数据的最佳解决方案是什么,因为它已经加载了家长?

最佳答案

ms-windows 上的多处理工作方式与类 UNIX 系统不同。

类UNIX系统具有fork系统调用,它可以复制当前进程。在具有写时复制虚拟内存管理的现代系统中,这甚至不是一个非常昂贵的操作。

这意味着父进程中的全局数据将与子进程共享,直到子进程写入该页面,在这种情况下它将被复制。

问题是 ms-windows 没有 fork。它有 CreateProcess 相反。所以在 ms-windows 上,会发生这种情况:

The parent process starts a fresh python interpreter process. The child process will only inherit those resources necessary to run the process objects run() method. In particular, unnecessary file descriptors and handles from the parent process will not be inherited. Starting a process using this method is rather slow compared to using fork or forkserver.

因此,由于您的函数中引用了全局数据,因此它将被加载。 但是每个子进程都会单独加载它

您可以尝试的是让您的进程使用 mmap 加载数据使用ACCESS_READ。我希望 ms-windows 内存子系统足够智能,只加载一次数据,以防多个进程加载同一个文件。

关于具有大共享数据的 Python 多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com