在没有 IPC 通信的情况下共享对象

Sharing an object without IPC communication

我想在父进程和它的子进程之间共享一个multiprocessing.Array

self.procs = [MP.Process(target=worker, kwargs=dict(sh_array=array)
              for _ in range(num_workers)]

上面的代码是否正确?当我访问共享数组时,我只想要基于共享内存/文件映射的快速 IPC 通信。我不希望幕后发生任何消息传递或基于副本的 IPC。那会破坏我正在编写的代码的目的。

另外,我想以相同的方式传递 class 的 不同实例 ,它们都引用同一个共享数组。这会正常工作还是我应该单独传递共享数组然后手动重建子进程中的对象?

Does the code above do the right thing?

是的,这正是 multiprocessing.Array 的用途和使用方式。

I don't want any IPC communication when I access the shared array.

我认为 "IPC" 一词在这里使用不正确。 IPC 代表 inter-process 通信,如果你有一个在进程之间共享的数组,那么你写入数组的任何内容都可以从其他进程读取。换句话说,您正在进程之间进行通信。换句话说,IPC。共享内存就是IPC,如果不想要IPC,那么进程之间就不能共享东西了。

你的意思可能完全不同。也许您不想来回传递消息或类似的东西?

Also, I'd like to pass the same way different instances of a class which all refer to the same shared array. Will this work correctly or should I pass the shared array separately and then rebuild the objects in the child processes manually?

两种方法都行。选择使代码更自然可读的选项。