Skip to main content
 首页 » 编程设计

python pool.map_async 不等待 .wait()

2024年12月31日25thcjp

我正在尝试运行一个与 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 

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

请您参考如下方法:

首先,如果您要立即等待,您可能不需要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 方法,那么您将看不到它。