为什么 mulitprocessing.Pool 运行 但永远不会终止?

Why does mulitprocessing.Pool run but never terminate?

我正在尝试使用 mulitprocessing.Pool 来加速跨一系列输入的函数执行。这些进程似乎已被调用,因为我的任务管理器指示我的 CPU 的利用率大幅增加,但任务从未终止。无论是运行时还是其他情况,都不会引发异常。

from multiprocessing import Pool

def f(x):
    print(x)
    return x**2

class Klass:
    def __init__(self):
        pass

    def foo(self):
        X = list(range(1, 1000))
        with Pool(15) as p:
            result = p.map(f, X)

if __name__ == "__main__":
    obj = Klass()
    obj.foo()
    print("All Done!")

有趣的是,尽管 CPU 利用率有所上升,print(x) 却从未向控制台打印任何内容。

我已按照建议 , to no avail. I have tried adding p.close() and p.join() as well with no success. Using other Pool class methods like imap lead to TypeError: can't pickle _thread.lock objects errors and seems to take a step away from the example usage in the introduction of the Python Multiprocessing Documentation.

将函数 f 移到了 class 之外

更令人困惑的是,如果我尝试 运行 上面的代码足够多次(每次尝试后都会杀死挂起的内核),代码就会开始按预期持续工作。在 "clicks" 到位之前通常需要大约二十次尝试。重新启动我的 IDE 会将现在的功能代码恢复到以前的损坏状态。作为参考,我 运行 在 Windows 10 上使用 Anaconda Python 发行版 (Python 3.7) 和 Spyder IDE。我的 CPU 有16 个内核,因此 Pool(15) 没有比我拥有的 CPU 个内核调用更多的进程。但是,运行 具有不同 IDE 的代码,如 Jupyter Lab,会产生相同的错误结果。

这可能是 Spyder 本身的一个缺陷,但是使用 mulitprocessing.Pool 而不是 mulitprocessing.Process 的建议似乎也不起作用。

这似乎是 Spyder 和 Jupyter 都有的问题。如果您直接在控制台中 运行 以上代码,一切都会按预期进行。

可能与 python 文档中的 this 有关:

Note Functionality within this package requires that the main module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.pool.Pool examples will not work in the interactive interpreter.

然后对他们的例子发表评论:

If you try this it will actually output three full tracebacks interleaved in a semi-random fashion, and then you may have to stop the master process somehow.

更新: 找到的信息 here 似乎证实了使用交互式解释器的池会取得不同程度的成功。此指南也已共享...

...guidance [is] to always use functions/classes whose definitions are importable.

这是 概述的解决方案,使用您的代码对我(每次)都有效。