【问题标题】:Python multiprocessing.Pool: how to join the reasults in a parallel way?Python multiprocessing.Pool:如何以并行方式加入结果?
【发布时间】: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


【解决方案1】:

Multiprocessing pool 将是您的选择。

以下是一些示例代码,希望对您有所帮助。您还可以查看另一个我的答案以查看更多详细信息。 How can I make my python code run faster

    from multiprocessing import Pool
    import time

    def foo_pool(x):
        return x*x

    def main():
         pool = Pool(4)
         sampleData = [x for x in range(9)]
         results = pool.map(foo_pool, sampleData)
         pool.close()
         pool.join()
         print(results)

    if __name__ == '__main__':
         main()

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多