【问题标题】:python pool.map_async doesn't wait for .wait()python pool.map_async 不等待 .wait()
【发布时间】:2018-05-28 20:06:47
【问题描述】:

我正在尝试运行一个与 pool.apply_async 配合得很好的胖函数

现在,我正在尝试 pool.map_async 函数(通过 functools.partial 方法传递了 2 个参数),程序立即结束,没有任何错误或异常......

    files = list_files(mypath) # list of files to process
    csv_rows = None
    result = mp.Queue() #result queue from multiprocessing module

    pool = mp.Pool(4)
    t = pool.map_async( partial(process_file, result), files)
    t.wait() # it doesn't wait HERE ... program exits immediately - no errors

关于我可能遗漏什么的任何线索?

【问题讨论】:

  • 告诉我们process_file。另外,如果您只想立即等待,不妨改用pool.map()
  • 您可能确实在某处的process_file 中有错误,但在您在t 上调用get 之前,您不会在主进程中看到异常。
  • @Blckknght 你能给我举个例子吗?我是多处理库的新手 ,,,
  • @AlexHall 地图的阻塞部分是否意味着我要等到所有 1000 多个进程都完成?即使我知道它们都是令人尴尬的平行?
  • 试试t.get()。它已记录在案(与您已经调用的 wait 方法一起)right here

标签: python python-3.x python-multiprocessing


【解决方案1】:

首先,如果您要立即使用wait,您可能不需要map_async。如果是这种情况,那么只需使用map。您还可以删除您的 queue 并返回值。但这可能不是您遇到的问题。

问题可能是wait 方法不会引发远程异常。您的 process_file 方法很可能实际上在池进程中失败,但您没有看到这些异常。就像提到的 Blckknght 一样,您应该切换到使用get 方法,正如您所看到的here,将引发远程异常。这是一个简单的示例,其中wait 方法隐藏了远程进程异常,以及如果切换到get 可以再次看到它们:

import multiprocessing as mp

def just_dies(n):
    raise ValueError("Test")

if __name__ == "__main__":
    pool = mp.Pool(4)
    results = pool.map_async(just_dies, range(10))

    # the wait will immediately silently pass
    #results.wait()

    # this will actually raise the remote exception
    results.get()

如果你运行它,你会得到一个类似这样的回溯错误消息

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "foo.py", line 14, in <module>
    results.get()
  File "XXX/python3.5/multiprocessing/pool.py", line 608, in get
    raise self._value
ValueError: Test

如果您切换到使用wait 方法,那么您将看不到它。

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2015-01-04
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多