调试代码花了我一晚上的时间,终于发现了这个棘手的问题。请看下面的代码。
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]]
?
最佳答案
如果您使用 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
如果您希望每次都调用回调。
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()
关于python - 回调函数在多处理 map_async 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19699165/