与相比Pool.apply
,该Pool.apply_async
方法还具有一个回调,如果提供该回调,则在函数完成时调用该回调。可以使用它来代替get()
。
例如:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
可能会产生如下结果
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
请注意,与不同pool.map
,结果的顺序可能与pool.apply_async
调用的顺序不同。但是有一个技巧可以排序:
import multiprocessing as mp
import time
def foo_pool(index,x):
time.sleep(2)
return [index, x*x] # 返回之中加入 index
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (index, i,), callback = log_result)
pool.close()
pool.join()
# 然后根据 result_list 每个元素的第一个值(即我们放入的index)排序
result_list = sorted(result_list, key=lambda k: dic[0])
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()