【问题标题】:How to get result from Pool.starmap_async()?如何从 Pool.starmap_async() 中获取结果?
【发布时间】:2019-10-20 15:49:15
【问题描述】:

我有一个程序计算数组*值的索引并返回一个字符串。我使用.starmap_async() 因为我必须将两个参数传递给我的异步函数。程序如下:

import multiprocessing as mp
from multiprocessing import freeze_support

def go_async(self, index, value) :
        return str(index * int(value))

def log_result(self, result):
        print("Succesfully get callback! With result: ", result)

def main() :
    array = [1,3,4,5,6,7]
    pool = mp.Pool() 
    res = pool.starmap_async(go_async, enumerate(array), callback = log_result)        
    print("Final result: ", res)
    pool.close()
    pool.join()

if __name__ == '__main__':    
    freeze_support()
    main()

我想得到一个 str 数组的结果:

res = ['0', '3', '8', '15', '24', '35']

但我只有结果:

最终结果:multiprocessing.pool.MapResult 对象位于 0x000001F7C10E51D0

如何正确地从.starmap_async() 获取价值? 此外,回调不会引发。

【问题讨论】:

    标签: python asynchronous multiprocessing python-multiprocessing starmap


    【解决方案1】:

    Pool 的异步方法返回的对象在概念上是"explicit futures",您需要调用.get() 来等待并接收实际结果。 所以res.get() 会给你你的结果。您还需要从您的函数中删除self,因为您没有在您的星图调用中传递一个实例。这目前会导致您的目标函数中出现异常,这也是您的回调未触发的原因。

    【讨论】:

    • 酷,这对我来说是一个解决方案。
    猜你喜欢
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2012-04-10
    相关资源
    最近更新 更多