一个消息队列应该在子进程中实例化还是在父进程中实例化?

Should a message queue be instantiated in the child process or the parent process?

现在,当我生成一个子进程时,我在父进程中实例化一个消息队列,并在构造函数参数中将其传递给子进程,如下所示:

import multiprocessing as mp

class testProcess(mp.Process):
    def __init__(self, msgQueue):
        mp.Process.__init__(self, daemon=True)
        self.msgQueue = msgQueue    

if __name__ == "__main__":
    # Instantiate queue in parent process and pass to child:
    msgQueue = mp.Queue()
    t = testProcess(msgQueue)

我这样做是因为我在学习如何使用多处理时看到的所有示例都是这样做的。

但是,我现在有很多子进程,在父进程中生成一堆队列并跟踪它们变得有点丑陋。在子进程的 __init__ 方法中生成队列会更干净,并在父进程中作为子进程命名空间的一部分简单地访问它,如下所示:

import multiprocessing as mp

class testProcess(mp.Process):
    def __init__(self):
        mp.Process.__init__(self, daemon=True)
        # Instantiate queue from within child __init__:
        self.msgQueue = mp.Queue()


if __name__ == "__main__":
    t = testProcess()
    # Now I can access the queue like so:
    t.msgQueue.put("hi there child")

我猜从技术上讲,进程 class 的 __init__ 语句无论如何都在父进程中执行(我认为?),所以我认为它不会有任何不同。

所以,我的问题是,如果我在子进程 __init__ 语句中实例化队列,以后是否会遇到某种问题?这两种方式都有什么优势吗?或者它们是等价的?

这没有什么区别,因为就像您已经写过的那样,Process.__init__() 在 parent 中执行。

这意味着问题标题:

"Should a message queue be instantiated in the child process or the parent process?"

是错误的,因为它发生在 parent 过程中。

这只是代码组织的问题,对于 per-process 连接,您的第二个代码片段很有意义。

如果您真的需要每个进程一个连接,您可以切换到 multiprocessing.Pipe 以提高性能。常规 multiprocessing.Queue 在第一个 .put() 上生成一个 feeder-thread,您不需要 single-producer/single-consumer (SPSC) 连接。