如何将函数的 return 值附加到池中的列表中?

How to append return value of function into list in Pool?

我很好奇是否可以将函数 f(x,y) 中的 return 值附加到列表中。

所以我有这个:

平行:

 def download_unit_LVs(self, cislo_uzemia):
     pool = Pool(number_of_workers)
     for cislo in cisla:
         pool.apply_async(self.download_cislo, args=(cislo_uzemia,cislo))
     pool.close()
     pool.join()
     self.manager.commit()

这就是我 运行 方法 self.download_cislo 并行的方式,但问题是,它 return 是一个我必须附加到结果列表的值。

怎么做?

顺序:

 def download_unit_LVs(self, cislo_uzemia):
        results = []
        for cislo in cisla:
            results.append(self.download_cislo(cislo_uzemia,cislo))
        self.manager.commit()

pool.apply_async 调用可以传递 callback 函数。这 foo 函数完成时将调用回调函数,并将 传递了由 foo 编辑的值 return。请注意 return 值 must be picklable,因为进程之间的通信是通过队列完成的。

import multiprocessing as mp

def foo(x):
    return x * x

if __name__ == '__main__':
    result = []
    pool = mp.Pool()
    for i in range(100):
        pool.apply_async(foo, args=(i, ), callback=result.append)
    pool.close()
    pool.join()
    print(result)
    # [0, 1, 4, 9, 16, ... 9409, 9604, 9801]

如果结果应在列表中结束,请使用 Pool:

map() 方法
def download_unit_LVs(self, cislo_uzemia):
    pool = Pool(number_of_workers)
    results = pool.map(partial(self.download_cislo, cislo_uzemia), self.cisla)
    self.manager.commit()

partial() 来自 functools 模块。