<blockquote>
<p>is there a variant of pool.map which support multiple arguments?</p>
</blockquote>
<p>Python 3.3包括<a href="http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap" rel="noreferrer">^{<cd1>} method</a>:</p>
<pre><code>#!/usr/bin/env python3
from functools import partial
from itertools import repeat
from multiprocessing import Pool, freeze_support
def func(a, b):
return a + b
def main():
a_args = [1,2,3]
second_arg = 1
with Pool() as pool:
L = pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
M = pool.starmap(func, zip(a_args, repeat(second_arg)))
N = pool.map(partial(func, b=second_arg), a_args)
assert L == M == N
if __name__=="__main__":
freeze_support()
main()
</code></pre>
<p>对于旧版本:</p>
<pre><code>#!/usr/bin/env python2
import itertools
from multiprocessing import Pool, freeze_support
def func(a, b):
print a, b
def func_star(a_b):
"""Convert `f([1,2])` to `f(1,2)` call."""
return func(*a_b)
def main():
pool = Pool()
a_args = [1,2,3]
second_arg = 1
pool.map(func_star, itertools.izip(a_args, itertools.repeat(second_arg)))
if __name__=="__main__":
freeze_support()
main()
</code></pre>
<h3>输出</h3>
<pre><code>1 1
2 1
3 1
</code></pre>
<p>注意这里如何使用<a href="https://docs.python.org/2.7/library/itertools.html#itertools.izip" rel="noreferrer">^{<cd2>}</a>和<a href="https://docs.python.org/2.7/library/itertools.html#itertools.repeat" rel="noreferrer">^{<cd3>}</a>。</p>
<p>由于<a href="http://bugs.python.org/issue5228" rel="noreferrer">the bug mentioned by @unutbu</a>不能在Python 2.6上使用<a href="http://docs.python.org/library/functools.html#functools.partial" rel="noreferrer">^{<cd4>}</a>或类似的功能,因此应该显式定义简单包装函数<code>func_star()</code>。另请参见<a href="http://paste.pocoo.org/show/351774/" rel="noreferrer">the workaround</a><a href="http://bugs.python.org/issue5228#msg130548" rel="noreferrer">suggested by ^{<cd6>}</a>。</p>