使用 ProcessPoolExecutor 进行并行处理

Parallel processing with ProcessPoolExecutor

我有一大堆必须以某种方式处理的元素。 我知道可以通过 multiprocessing 的 Process 来完成:

pr1 = Process(calculation_function, (args, ))
pr1.start()
pr1.join()

所以我可以创建假设 10 个进程并将参数按 10 分割传递给 args。然后工作就完成了。

但我不想手动创建和手动计算。相反,我想使用 ProcessPoolExecutor 并且我是这样做的:

executor = ProcessPoolExecutor(max_workers=10)
executor.map(calculation, (list_to_process,))

计算是我完成这项工作的功能。

def calculation(list_to_process):
    for element in list_to_process:
        # .... doing the job

list_to_process 是我要处理的列表。

但是在 运行 这段代码之后,循环迭代只进行了一次。 我认为

executor = ProcessPoolExecutor(max_workers=10)
executor.map(calculation, (list_to_process,))

同此10次:

pr1 = Process(calculation, (list_to_process, ))
pr1.start()
pr1.join()

不过好像不对。

ProcessPoolExecutor如何实现真正的多进程?

calculation 函数中删除 for 循环。现在您正在使用 ProcessPoolExecutor.mapmap() 调用 您的循环,不同之处在于列表中的每个元素都被发送到不同的进程。例如

def calculation(item):
    print('[pid:%s] performing calculation on %s' % (os.getpid(), item))
    time.sleep(5)
    print('[pid:%s] done!' % os.getpid())
    return item ** 2

executor = ProcessPoolExecutor(max_workers=5)
list_to_process = range(10)
result = executor.map(calculation, list_to_process)

您会在终端中看到如下内容:

[pid:23988] performing calculation on 0
[pid:10360] performing calculation on 1
[pid:13348] performing calculation on 2
[pid:24032] performing calculation on 3
[pid:18028] performing calculation on 4
[pid:23988] done!
[pid:23988] performing calculation on 5
[pid:10360] done!
[pid:13348] done!
[pid:10360] performing calculation on 6
[pid:13348] performing calculation on 7
[pid:18028] done!
[pid:24032] done!
[pid:18028] performing calculation on 8
[pid:24032] performing calculation on 9
[pid:23988] done!
[pid:10360] done!
[pid:13348] done!
[pid:18028] done!
[pid:24032] done!

虽然事件的顺序实际上是随机的。由于某种原因,return 值(至少在我的 Python 版本中)实际上是一个 itertools.chain 对象。但这是一个实现细节。您可以 return 列表形式的结果,例如:

>>> list(result)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

在您的示例代码中,您传递了一个单元素元组 (list_to_process,),这样就可以将您的完整列表传递给一个进程。