你能做到这一点的唯一方法是,如果 func 知道 Pool.map 方法中使用的 iterable 的最后一个元素是什么,并且没有干净的方法可以做到这一点.为什么不直接提交一个单独的任务来处理需要为最后一个值完成的额外工作?假设一切都可以并行运行,您可能希望将map_async 和apply_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)