我正在寻找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中有这样的库吗?我找不到一个。
我想你想要的是收集结果,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]