Python的Fork-join模型实现? (相当于Java的ForkJoinPool)

问题描述 投票:2回答:1

我正在寻找Python的fork-join model的实现。作为Java的ForkJoinPool,它应该允许以递归方式将任务的工作拆分(分叉)为几个子任务。子任务完成后,结果将被连接并返回。理想情况下,它应该支持类似于concurrent.futures中的ThreadPoolExecutor和ProcessPoolExecutor的线程和进程,但线程现在更重要。它必须允许限制线程数(我希望每个核心有一个线程)。我知道这只有在代码发布GIL时才有用。

来自维基百科的例子阐明了fork-join模型:

solve(problem):
    if problem is small enough:
        solve problem directly (sequential algorithm)
    else:
        for part in subdivide(problem)
            fork subtask to solve(part)
        join all subtasks spawned in previous loop
        return combined results

Python中有这样的库吗?我找不到一个。

python python-3.x parallel-processing fork-join
1个回答
0
投票

我想你想要的是收集结果,multiprocessing.starmap()可能是选择,这里举例说明

import multiprocessing as mp

def func(x, y):
    return x + y

l = list()
with mp.Pool(mp.cpu_count()) as p:
    l = p.starmap(func, [(1,2), (2,3), (3,4)])

print(l)  # result in [3, 5, 7]
© www.soinside.com 2019 - 2024. All rights reserved.