python - 为什么 multiprocessing.Pool 运行但从未终止?

标签 python multiprocessing jupyter spyder pool

我正在尝试使用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) 却从未向控制台打印任何内容。

我已按照建议将函数 f 移到类之外 here ,无济于事。我也尝试添加 p.close()p.join() 但没有成功。使用其他 Pool 类方法(例如 imap)会导致 TypeError: can't pickle _thread.lock objects 错误,并且似乎远离了Python Multiprocessing Documentation 简介中的示例用法.

更令人困惑的是,如果我尝试运行代码超过足够的次数(每次尝试后杀死挂起的内核),代码就会开始按预期一致工作。通常需要大约二十次尝试才能“咔嗒”一声到位。重新启动 IDE 会将现在可用的代码恢复到之前损坏的状态。作为引用,我在 Windows 10 上使用 Anaconda Python Distribution (Python 3.7) 和 Spyder IDE 运行。我的 CPU 有 16 个核心,因此 Pool(15) 不会调用比我更多的进程有CPU核心。但是,使用不同的 IDE(例如 Jupyter Lab)运行代码会产生相同的损坏结果。

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

最佳答案

可能与this相关来自 python 文档:

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.

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

关于python - 为什么 multiprocessing.Pool 运行但从未终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61662423/

相关文章:

python - Jupyter notebook 不运行代码。停留在 [*]

python - 什么是 "ANSI_X3.4-1968"编码?

python - 在关系数据库中查找统计相关性

python - 查找文本是否突出显示

jupyter-notebook - 启动器中的 fatal error : Unable to create process using '"'

python - 如何检查是否使用 conda 或 pip 安装了 Python、pandas 和 Jupyter?我应该用 conda 重新安装它吗?

python - 在序列化器中创建访问另一个模型属性的新字段

python - 在 python : About several instances with same name at the same time 中使用池进行多处理

c - 使用后如何正确删除信号量?

具有可迭代和多个参数的 Python 多处理