运行 Python 中的并行函数

running a function in parallel in Python

我试图在 Python 中并行 运行 类似 f 的函数,但有两个问题:

  1. 使用 map 时,函数 f 不会应用于数组 ab.
  2. 的所有置换元组
  3. 尝试使用 Pool 时,出现以下错误:
TypeError: '<=' not supported between instances of 'tuple' and 'int'
def f(n,m):
    x = n * m
    return x

a = (1,2,3,4,5)
b = (3,4,7,8,9)
result = map(f, a, b)
print(list(result))

#now trying parallel computing
from multiprocessing import Pool
pool = Pool(processes=4)
print(*pool.map(f, a, b))

我没有对您的 #1 问题进行任何更改,使用 map() 得到了预期的结果。您似乎对它的工作原理有错误的假设,但没有为您的示例提供预期结果与实际结果。

对于 #2 到 return 与 #1 相同的答案,您需要 starmap() 而不是 map() 此实例的 multiprocessing 使用,然后 zip() 参数列表以提供参数集。如果在 OS 上没有 fork(并且为了便携性,如果你是),运行 全局代码仅当它是主进程时,而不是通过使用 有记载if __name__ == '__main__':成语:

from multiprocessing import Pool

def f(n,m):
    x = n * m
    return x

if __name__ == '__main__':
    a = (1,2,3,4,5)
    b = (3,4,7,8,9)
    result = map(f, a, b)
    print(list(result))

    #now trying parallel computing
    pool = Pool(processes=4)
    print(*pool.starmap(f, zip(a, b)))

输出:

[3, 8, 21, 32, 45]
3 8 21 32 45

如果您确实想要#1 中提到的排列,请使用 itertools.starmappool.starmap 并将 itertools.product(a,b) 作为参数。