Python多重处理:并行运行多个for循环的每个迭代

用户名

我在python中有两个循环。这是一些伪代码。我想同时运行这些功能和每个功能的每个迭代。因此,在此示例中,一次将有8个进程。我知道您可以使用“ Process”,但是我只是不知道如何合并一个可迭代对象。请让我知道,谢谢!

import...

def example1(iteration):
    print('stuff')

def example2(iteration):
    print('stuff')

if __name__ == '__main__':  
    freeze_support()
    pool = multiprocessing.Pool(4)
    iteration = [1,2,3,4]
    pool.map(example1,iteration)

埃德温·谢泼德

假设不需要在我想同时启动它们的时间map_async

在下面的示例中,即使首先启动,我们也可以打印example2之前example1完成的结果example1

import multiprocessing
import time

def example1(iteration):
    time.sleep(1)
    return 1

def example2(iteration):
    return 2

if __name__ == '__main__':
    pool = multiprocessing.Pool(4)
    iteration = [1,2,3,4]
    result1 = pool.map_async(example1, iteration)
    result2 = pool.map_async(example2, iteration)
    print(result2.get())
    print(result1.get())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章