【发布时间】:2017-02-28 03:24:56
【问题描述】:
我已阅读 Python multiprocessing.Pool: when to use apply, apply_async or map?,它很有用,但仍有我自己的问题。在下面的代码中,我希望 result_list.append(result) 以并行方式进行,我希望 4 个处理器并行追加结果并将 4 个列表转换为 1 个列表。
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(4)
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()
【问题讨论】:
-
用 4 个处理器生成 4 个列表然后将 4 个列表合并为 1 个列表是否更容易?
-
这正是我想要的,如何实现?
-
我不确定我是否明白你在问什么。听起来你想要
pool.map。子进程无法附加到结果列表中,因为列表存在于主进程的内存中(不与其他进程共享)。有一些同步类型可能需要一些额外的努力(例如multiprocessing.Array),但我怀疑安全地使用它们需要相当多的开销。使用pool.map比您自己组装的类似系统更容易并且可能更快。
标签: python multithreading python-3.x multiprocessing