与相比Pool.apply,该Pool.apply_async方法还具有一个回调,如果提供该回调,则在函数完成时调用该回调。可以使用它来代替get()

    例如:

    1. import multiprocessing as mp
    2. import time
    3. def foo_pool(x):
    4. time.sleep(2)
    5. return x*x
    6. result_list = []
    7. def log_result(result):
    8. # This is called whenever foo_pool(i) returns a result.
    9. # result_list is modified only by the main process, not the pool workers.
    10. result_list.append(result)
    11. def apply_async_with_callback():
    12. pool = mp.Pool()
    13. for i in range(10):
    14. pool.apply_async(foo_pool, args = (i, ), callback = log_result)
    15. pool.close()
    16. pool.join()
    17. print(result_list)
    18. if __name__ == '__main__':
    19. apply_async_with_callback()

    可能会产生如下结果

    1. [1, 0, 4, 9, 25, 16, 49, 36, 81, 64]

    请注意,与不同pool.map,结果的顺序可能与pool.apply_async调用的顺序不同。但是有一个技巧可以排序:

    1. import multiprocessing as mp
    2. import time
    3. def foo_pool(index,x):
    4. time.sleep(2)
    5. return [index, x*x] # 返回之中加入 index
    6. result_list = []
    7. def log_result(result):
    8. # This is called whenever foo_pool(i) returns a result.
    9. # result_list is modified only by the main process, not the pool workers.
    10. result_list.append(result)
    11. def apply_async_with_callback():
    12. pool = mp.Pool()
    13. for i in range(10):
    14. pool.apply_async(foo_pool, args = (index, i,), callback = log_result)
    15. pool.close()
    16. pool.join()
    17. # 然后根据 result_list 每个元素的第一个值(即我们放入的index)排序
    18. result_list = sorted(result_list, key=lambda k: dic[0])
    19. print(result_list)
    20. if __name__ == '__main__':
    21. apply_async_with_callback()