multiprocessing.Pool 在 jupyter 笔记本中适用于 linux 但不适用于 windows

multiprocessing.Pool in jupyter notebook works on linux but not windows

我正在尝试 运行 一些独立的计算(尽管从相同的数据中读取)。当我在 Ubuntu 上 运行 但在 Windows(windows 服务器 2012 R2)上不工作时,我的代码有效,我收到错误:

'module' object has no attribute ...

当我尝试使用 multiprocessing.Pool 时(它出现在内核控制台中,而不是笔记本本身的输出)

(我已经犯了在创建池后定义函数的错误,我也更正了它,这不是问题)。

即使在最简单的示例中也会发生这种情况:

from multiprocessing import Pool
def f(x):
    return x**2
pool = Pool(4)
for res in pool.map(f,range(20)):
    print res

我知道它需要能够导入模块(我不知道在笔记本上工作时它是如何工作的),我听说过IPython.Parallel,但我一直无法查找任何文档或示例。

欢迎任何solutions/alternatives。

我会post将此作为评论,因为我没有完整的答案,但我会在弄清楚发生了什么后进行修改。

from multiprocessing import Pool

def f(x):
    return x**2

if __name__ == '__main__':
    pool = Pool(4)
    for res in pool.map(f,range(20)):
        print(res)

这行得通。我相信这个问题的答案是here。简而言之,子进程不知道它们是子进程,并试图递归地 运行 主脚本。

这是我给出的错误,它给了我们相同的解决方案:

RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.