【问题标题】:Is there any way to select the last process of multiple processes in a pool to perform an extra task?有没有办法选择池中多个进程的最后一个进程来执行额外的任务?
【发布时间】:2021-05-31 10:06:57
【问题描述】:

有什么方法可以让 func(x) 中运行的最后一个进程执行除了 return x*x 之外的额外任务?

from multiprocessing import Pool

def func(x):
    # to let the last process run here perform extra task other than return x*x
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(func, [1, 2, 3]))

【问题讨论】:

  • 什么样的任务?也是对数字的数学运算?
  • 是的。例如清空一个变量。

标签: python parallel-processing multiprocessing python-multiprocessing


【解决方案1】:

你能做到这一点的唯一方法是,如果 func 知道 Pool.map 方法中使用的 iterable 的最后一个元素是什么,并且没有干净的方法可以做到这一点.为什么不直接提交一个单独的任务来处理需要为最后一个值完成的额外工作?假设一切都可以并行运行,您可能希望将map_asyncapply_async 分别用于这两个任务,并且如果您希望在其中一个任务完成后立即打印出结果,那么您应该指定一个或多个回调例程取决于为 iterable 的最后一个元素执行的额外工作是否需要打印一些内容或返回一些结果:

from multiprocessing import Pool

def func(x):
    # to let the last process run here perform extra task other than return x*x
    return x*x

def func2(x):
    # perform extra function with last argument
    ...

def callback1(result):
    """ return value from map_async(func, etc.) """
    print(result)

def callback2(result):
    """ return value from func2 """
    ...

if __name__ == '__main__':
    with Pool(4) as p: # you only need 4 processes
        p.map_async(func, [1, 2, 3], callback=callback1)
        # provide argument to func2, if needed, and a callback, if needed
        p.apply_async(func2, args=(3,), callback=callback2)
        # wait for both of the above submitted tasks to complete:
        p.close()
        p.join()

如果您不关心一有结果就打印出来,那么您不需要使用回调函数:

if __name__ == '__main__':
    with Pool(4) as p: # you only need 4 processes
        result1 = p.map_async(func, [1, 2, 3])
        # provide argument to func2, if needed
        result2 = p.apply_async(func2, args=(3,))
        # wait for both of the above submitted tasks to complete:
        print(result1.get()) # return value from map call
        print(result2.get()) # or just result2.get() if return value is not interesting

但是,如果对最后一个参数进行的额外处理只应在 map 调用完成后进行,则该额外处理应由主进程运行,并且不需要回调函数:

if __name__ == '__main__':
    with Pool(3) as p: # you only need 3 processes
        print(p.map(func, [1, 2, 3])
        func2(3)

【讨论】:

  • 这是否令人满意地回答了您的问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多