使并行代码在 python 2.7 和 3.6 中工作

Making parallel code work in python 2.7 and 3.6

我在 python 3.6 中有一些代码是这样的:

from multiprocessing import Pool
with Pool(processes=4) as p:
    p.starmap(parallel_function, list(dict_variables.items()))

此处 dict_variables 看起来像这样:

[('aa', ['ab', 'ab', 'ad']), ('aa1', ['a1b', 'a1b', 'a2d'])]

此代码仅适用于 python 3.6。我怎样才能让它在 2.7 中工作?

starmapintroduced in Python3.3. In Python2, use Pool.map 并自行解压缩参数:

在Python3中:

import multiprocessing as mp

def starmap_func(x, y):
    return x**y

with mp.Pool(processes=4) as p:
    print(p.starmap(starmap_func, [(1,2), (3,4), (5,6)]))
    # [1, 81, 15625]

在Python2或Python3中:

import multiprocessing as mp

def map_func(arg):
    x, y = arg
    return x**y

p = mp.Pool(processes=4)
print(p.map(map_func, [(1,2), (3,4), (5,6)]))
# [1, 81, 15625]
p.close()