我可以将map / imap / imap_unordered与没有参数的函数一起使用吗?

时间:2014-12-29 13:28:18

标签: python python-multiprocessing

有时我需要对没有参数的函数使用多处理。我希望我能做一些像:

from multiprocessing import Pool

def f():  # no argument
    return 1

# TypeError: f() takes no arguments (1 given)
print Pool(2).map(f, range(10))

我可以Process(target=f, args=()),但我更喜欢map / imap / imap_unordered的语法。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:7)

map函数的第一个参数应该是一个函数,它应该接受一个参数。它是强制性的,因为迭代将传递,因为第二个参数将被迭代,并且值将在每次迭代中逐个传递给函数。

所以,你最好的办法是重新定义f接受一个参数并忽略它,或者用一个参数写一个包装函数,忽略参数并返回f的返回值,就像这样

from multiprocessing import Pool

def f():  # no argument
    return 1

def throw_away_function(_):
    return f()

print(Pool(2).map(throw_away_function, range(10)))
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

您不能对池使用lamdba函数,因为它们不可选择。

答案 1 :(得分:2)

您可以像这样使用pool.starmap()代替.map()

from multiprocessing import Pool

def f():  # no argument
    return 1

print Pool(2).starmap(f, [() for _ in range(10)])

starmap将给定可迭代对象的所有元素作为参数传递给f。根据您的情况,可迭代项应该为空。

答案 2 :(得分:1)

使用Pool.apply_async时有什么问题吗?

with multiprocessing.Pool() as pool:
    future_results = [pool.apply_async(f) for i in range(n)]
    results = [f.get() for f in future_results]
相关问题