簡體   English   中英

使並行代碼在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中工作?

starmap在Python3.3引入的 在Python2中,使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM