首页 > 解决方案 > 多处理池挂在 jupyter 笔记本中

问题描述

我有一个非常简单的脚本,如下所示:

import multiprocessing as multi

def call_other_thing_with_multi():
    P = multi.Pool(3)
    P.map(other_thing, range(0,5))
    P.join()


def other_thing(arg):
    print(arg)
    return arg**2.

call_other_thing_with_multi()

当我调用它时,我的代码会永久挂起。这是在带有 python 2.7 的 Windows 上。

感谢您的任何指导!

标签: python-2.7multiprocessing

解决方案


根据文档,您需要先close()致电join()

import multiprocessing as multi

def call_other_thing_with_multi():
    P = multi.Pool(3)
    P.map(other_thing, range(0,5))
    P.close() # <-- calling close before P.join()
    P.join()
    print('END')

def other_thing(arg):
    print(arg)
    return arg**2.

call_other_thing_with_multi()

印刷:

0
1
2
3
4
END

编辑:更好的是使用上下文管理器,不要忘记调用close()

def call_other_thing_with_multi():
    with multi.Pool(3) as P:
        P.map(other_thing, range(0,5))
    print('END')

推荐阅读