使用Python的多处理:如何并行嵌套循环并将结果附加到字典?

使用Python的多处理:如何并行嵌套循环并将结果附加到字典?,python,python-multiprocessing,multiprocess,Python,Python Multiprocessing,Multiprocess,我不熟悉Python中的多处理,目前我不确定如何处理手中的问题。我试图实现一个有两个循环(内循环和外循环)的函数,并将结果附加到字典中。功能和我希望实现的功能如下所示: def func(p, a): return p*a p_dict = dict() for p in all_possible_ps: #I would like to parallelize this alist = list() for a in all_possible_as: #

我不熟悉Python中的多处理,目前我不确定如何处理手中的问题。我试图实现一个有两个循环(内循环和外循环)的函数,并将结果附加到字典中。功能和我希望实现的功能如下所示:

def func(p, a):
    return p*a

p_dict = dict()
for p in all_possible_ps:    #I would like to parallelize this
    alist = list()

    for a in all_possible_as:    #And this for loop
        alist.append(func(p,a))

    p_dict[p] = alist

对于内部循环,我相信我可以实例化一个池,
p=pool()
,然后
p.map(func,所有可能的)
来获得
alist
。我不知道如何并行两个循环,同时分配两个循环的进程数

这里有一个简单的方法。如果您使用的是Python2.7,则可以使用
multiprocessing.Pool

from concurrent.futures import ProcessPoolExecutor

p_dict = {}

# submit jobs
with ProcessPoolExecutor() as pool:
    for p in all_possible_ps:
        p_dict[p] = [pool.submit(func, p, a) for a in all_possible_as]

# collect results
for p, alist in p_dict.items():
    for ii, fut in enumerate(alist):
        alist[ii] = fut.result()

您可以使用两个不同的池,然后嵌套它们。在这里,我使用的是
pathos
(它包括一个
多处理的分支
,具有必要的序列化功能,可以在池中传递lambda)

如果你看一个for循环,有两个变量的函数,你可以想到这种级数

>>> doit = lambda x,y: x*y
>>> a = [0,1,2,3]
>>> b = [9,8,7,6]
>>> [[doit(i,j) for j in b] for i in a]
[[0, 0, 0, 0], [9, 8, 7, 6], [18, 16, 14, 12], [27, 24, 21, 18]]
要创建嵌套并行:

>>> from pathos.pools import ThreadPool, ProcessPool
>>> p = ProcessPool()
>>> t = ThreadPool()
>>> foo = lambda x,y: p.map(doit, [x]*len(y), y) 
>>> t.map(foo, a, [b]*4)
[[0, 0, 0, 0], [9, 8, 7, 6], [18, 16, 14, 12], [27, 24, 21, 18]]
imap
只是一个映射迭代器。如果您愿意,可以使用
map
,但我将使用下面的
imap
。我相信您特别需要的功能如下:

>>> bar = lambda x,y: (x, p.map(doit, [x]*len(y), y)) 
>>> res = t.imap(bar, a, [b]*4)
>>> adict = {}
>>> for i,j in res:
...   adict[i] = j
... 
>>> adict
{0: [0, 0, 0, 0], 1: [9, 8, 7, 6], 2: [18, 16, 14, 12], 3: [27, 24, 21, 18]}