33

调试代码花了我一晚上的时间,终于发现了这个棘手的问题。请看下面的代码。

from multiprocessing import Pool

def myfunc(x):
    return [i for i in range(x)]

pool=Pool()

A=[]
r = pool.map_async(myfunc, (1,2), callback=A.extend)
r.wait()

我以为我会得到A=[0,0,1],但输出是A=[[0],[0,1]]. 这对我来说没有意义,因为如果我有A=[]A.extend([0])就会A.extend([0,1])给我A=[0,0,1]。回调可能以不同的方式工作。所以我的问题是如何得到A=[0,0,1]而不是[[0],[0,1]]

4

1 回答 1

45

[[0], [0, 1]]如果您使用 map_async,则使用结果 () 调用一次回调。

>>> from multiprocessing import Pool
>>> def myfunc(x):
...     return [i for i in range(x)]
... 
>>> A = []
>>> def mycallback(x):
...     print('mycallback is called with {}'.format(x))
...     A.extend(x)
... 
>>> pool=Pool()
>>> r = pool.map_async(myfunc, (1,2), callback=mycallback)
>>> r.wait()
mycallback is called with [[0], [0, 1]]
>>> print(A)
[[0], [0, 1]]

apply_async如果您希望每次都调用回调,请使用。

pool=Pool()
results = []
for x in (1,2):
    r = pool.apply_async(myfunc, (x,), callback=mycallback)
    results.append(r)
for r in results:
    r.wait()
于 2013-10-31T05:55:17.877 回答