【问题标题】:Is there a way to accumulate the result of a pool.apply_async calls whenever it is available without collecting them in a list like structure?有没有办法在 pool.apply_async 可用时累积调用的结果而不将它们收集在类似结构的列表中?
【发布时间】:2019-10-17 17:20:37
【问题描述】:

在 for 循环中,我使用 python pool.apply_async() 调用发送作业。

下面的python代码最初是我写的,然后由@Santiago Magariños编辑

import multiprocessing
import numpy as np
from time import time, sleep
from random import random

chrNames=['chr1','chr2','chr3']
sims=[1,2,3]



def accumulate_chrBased_simBased_result(chrBased_simBased_result,accumulatedSignalArray,accumulatedCountArray):    
    signalArray = chrBased_simBased_result[0]
    countArray = chrBased_simBased_result[1]

    accumulatedSignalArray += signalArray
    accumulatedCountArray += countArray


def func(chrName,simNum):

    result=[]
    sleep(random()*5)
    signal_array=np.full((10000,), simNum, dtype=float)
    count_array = np.full((10000,), simNum, dtype=int)
    result.append(signal_array)
    result.append(count_array)
    print('%s %d' %(chrName,simNum))

    return result


if __name__ == '__main__':

    accumulatedSignalArray = np.zeros((10000,), dtype=float)
    accumulatedCountArray = np.zeros((10000,), dtype=int)

    numofProcesses = multiprocessing.cpu_count()
    pool = multiprocessing.Pool(numofProcesses)

    results = []
    for chrName in chrNames:
        for simNum in sims:
            results.append(pool.apply_async(func, (chrName,simNum,)))

    for i in results:
        print(i)

    while results:
        for r in results[:]:
            if r.ready():
                print('{} is ready'.format(r))
                accumulate_chrBased_simBased_result(r.get(),accumulatedSignalArray,accumulatedCountArray)
                results.remove(r)

    pool.close()
    pool.join()

    print(accumulatedSignalArray)
    print(accumulatedCountArray)

有没有办法在 pool.apply_async() 调用可用时累积结果而不将它们收集在类似结构的列表中?

【问题讨论】:

  • In the docs 可以看到有一个回调可以指定在结果准备好时运行。
  • 问题是我找不到很好的回调示例代码。在这种情况下,我需要将 apply_async 调用的结果累积在一些其他数据结构中,例如accumulatedSignalArray 和accumulatedCountArray。回调只接受一个输入。
  • 我建议使用pool.imap_unordered 而不是大量调用apply_async。它暴露了您似乎正在重新实现的界面
  • @SamMason 当您使用 pool.imap_unordered() 时,您必须在可迭代中一起提供所有数据,通过使用 pool.apply_sync() 您可以为每个调用提供数据,并且与回调一起提供您不需要收集它返回的东西。因此,pool.apply_sync() 似乎比 pool.imap_unordered() 更好
  • 我不确定两者是否“更好”。在您的问题中,您想在一组网格参数上运行单个函数并收集结果。这是一个常见的操作,因此 map 方法家族试图让这种事情变得更容易。

标签: python multiprocessing


【解决方案1】:

这样的事情可能会奏效。几乎复制您的代码并添加回调,请注意这是有效的,因为池是在我们访问累加器值之前加入的。如果不是,我们需要一些其他类型的同步机制

class Accumulator:
    def __init__(self):
        self.signal = np.zeros((10000,), dtype=float)
        self.count = np.zeros((10000,), dtype=int)

    def on_result(self, result):
        self.signal += result[0]
        self.count += result[1]

if __name__ == '__main__':

    num_proc = multiprocessing.cpu_count()
    pool = multiprocessing.Pool(num_proc)

    accumulator = Accumulator()
    for chrName in chrNames:
        for simNum in sims:
            pool.apply_async(func, (chrName,simNum,), callback=accumulator.on_result)

    pool.close()
    pool.join()

    print(accumulator.signal)
    print(accumulator.count)

【讨论】:

  • 我们不需要像 result.get()[0] 这样的东西吗?
  • @burcak 不,它将结果值直接传递给回调。您之前需要调用get 的唯一原因是因为在调用时结果尚未准备好,因此库为您提供了“未来”结果的句柄。您在以后调用 get 以访问实际结果。
  • 你的意思是当回调发送结果时它总是准备好,因此不需要调用get()?谢谢。
  • @burcak 是的,这就是回调的目的。当结果准备好时被调用。
  • 我正在运行 pool.apply_async() 的代码,在 for 循环中调用 pool.apply_async(),但它似乎只使用一个处理器,其他所有处理器都在休眠。这可能是什么原因?
猜你喜欢
  • 2020-02-13
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 2023-01-24
  • 2012-08-02
相关资源
最近更新 更多