我正在寻找一个Python的fork-join model实现。作为Java的ForkJoinPool,它应该允许以递归方式将任务的工作拆分(fork)为多个子任务。子任务完成后,将连接并返回结果。理想情况下,它应该支持类似于concurrent.futures中的ThreadPoolExecutor和ProcessPoolExecutor的线程和进程,但目前线程更重要。它必须允许限制线程的数量(我希望每个核心有一个线程)。我知道只有当代码释放GIL时,这才是有用的。
来自Wikipedia的示例来阐明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中有这样的库吗?我找不到一个。
发布于 2019-03-01 14:29:33
我认为您需要的是收集结果,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]https://stackoverflow.com/questions/54938449
复制相似问题