【问题标题】:multiprocessing pool hangs in jupyter notebook多处理池挂在 jupyter 笔记本中
【发布时间】:2019-11-08 19:53:41
【问题描述】:

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

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.7 multiprocessing


    【解决方案1】:

    按照documentation,你需要在join()之前调用close()

    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')
    

    【讨论】:

    • 这个其实也挂了
    • @jasonm 你运行的是完全相同的代码吗?我在 Python 3.6 上,但应该没什么区别。我添加了带有上下文管理器的版本。
    • 是的,运行相同的代码。它不起作用,并且上下文在 py27 中不起作用,如所示。 stackoverflow.com/questions/25968518/…
    • 我的问题措辞不当,您的解决方案确实有效。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2020-04-11
    • 2020-06-11
    • 1970-01-01
    • 2021-09-18
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多