回调函数如何在多处理map_async中工作?

问题描述 投票:24回答:1

我花了一整夜的时间调试我的代码,终于找到了这个棘手的问题。请查看下面的代码。

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]]

python multiprocessing pool
1个回答
38
投票

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

>>> 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。>>

apply_async
© www.soinside.com 2019 - 2024. All rights reserved.