【问题标题】:Python: Why does Pool.map() hang when attempting to use the input arguments to its map function?Python:为什么 Pool.map() 在尝试使用其 map 函数的输入参数时会挂起?
【发布时间】:2019-06-03 22:16:31
【问题描述】:

我有以下函数(为便于阅读而缩短),我使用 Python 的 (3.5) multiprocessing 模块对其进行并行化:

def evaluate_prediction(enumeration_tuple):
    i = enumeration_tuple[0]
    logits_pred = enumeration_tuple[1]
    print("This prints succesfully")
    print("This never gets printed: ")
    print(enumeration_tuple[0])
    filename = sample_names_test[i]
    onehots_pred = logits_to_onehots(logits_pred)
    np.save("/media/nfs/7_raid/ebos/models/fcn/" + channels + "/test/ndarrays/" + filename, onehots_pred)

但是,每当我尝试读取其输入参数时,此函数就会挂起。执行可以越过logits_pred = enumeration_tuple[1] 行,打印语句打印一个简单的字符串就证明了这一点,但只要我print(logits_pred),它就会停止。显然,每当我真正需要传递的值时,该过程就会停止。我没有收到异常或错误消息。当使用 Python 的内置 map() 函数或 for 循环时,函数会成功完成。我应该有足够的内存和计算能力。所有进程都在写入不同的文件。 enumerate(predictions) 产生正确的索引值对,正如预期的那样。我使用Pool.map() 调用这个函数:

pool = multiprocessing.Pool()
file_results = pool.map(evaluate_prediction, enumerate(predictions))

为什么挂了?我怎样才能得到一个异常,所以我知道出了什么问题?

更新:将映射函数外包给另一个模块,从那里导入它,并将__init__.py 添加到我的目录后,我设法打印了元组中的第一项,而不是第二项。

【问题讨论】:

    标签: python multiprocessing arguments


    【解决方案1】:

    我之前遇到过类似的问题,对我有用的解决方案是将要并行化的函数放在单独的模块中,然后导入。

    from eval_prediction import evaluate_prediction
    pool = multiprocessing.Pool()
    file_results = pool.map(evaluate_prediction, enumerate(predictions))
    

    我假设您将函数定义保存在同一目录中的文件名 eval_prediction.py 中。确保你也有 __init__.py。

    【讨论】:

    • 感谢您的回答!我现在走得更远了;我可以打印元组中的第一项,但它现在挂在第二项 (print(enumeration_tuple[1]))。
    猜你喜欢
    • 2016-05-06
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2016-08-12
    • 2021-01-07
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多