使用多个参数的python多处理

时间:2016-04-14 05:40:15

标签: python function parallel-processing multiprocessing pool

我可以使用多处理轻松设置对“func”的并行调用,如下所示:

import multiprocessing

def func(tup):
    (a, b) = tup
    return str(a+b)

pool = multiprocessing.Pool()
tups = [ (1,2), (3,4), (5,6), (7,8)]
results = pool.imap(func, tups)
print ", ".join(results)

给出结果:

3, 7, 11, 15

问题是我的实际函数“func”比这里的例子更复杂,所以我不想用一个“tup”参数来调用它。我想要多个参数以及关键字参数。我想要做的是如下所示,但列表中的“*”解包不起作用(并且也不支持关键字)

import multiprocessing

def func(a, b):
    return str(a+b)

pool = multiprocessing.Pool()
tups = [ *(1,2), *(3,4), *(5,6), *(7,8)]
results = pool.imap(func, tups)
print ", ".join(results)

所以...有没有办法在进行并行处理的同时获得python函数调用的所有功能?

2 个答案:

答案 0 :(得分:0)

你不能只使用dicts或对象吗?

import multiprocessing
def func(a):
     print(str(a['left'] + a['right']))

pool = multiprocessing.Pool()
i1 = {'left': 2, 'right': 5}
i2 = {'left': 3, 'right': 4}
pool.imap(func, [i1, i2])

这样您就不会在方法定义中定义关键字,但至少可以在方法体中引用关键字。功能输入也是如此。而不是处理元组,这更具可读性。

答案 1 :(得分:0)

HarryPotfleur的评论是正确的,基本上如果你使用的是Python 3.3+,你可以使用starmap

  

starmap (func,iterable [,chunksize])
  就像map()一样   迭代的元素应该是迭代的   解压缩为参数。

     

因此,[(1,2), (3, 4)]的可迭代结果为[func(1,2), func(3,4)]

只需将imap替换为starmap

如果您使用的是较低版本,则无法直接执行此操作。相反,您可以使用中间函数

def inter(tup):
    return func(*tup)

def func(a, b, c):
    return str(a+b+c)