how does the callback function work in python multiprocessing map_async

南笙酒味 提交于 2020-01-09 09:02:52

问题


It cost me a whole night to debug my code, and I finally found this tricky problem. Please take a look at the code below.

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()

I thought I would get A=[0,0,1], but the output is A=[[0],[0,1]]. This does not make sense to me because if I have A=[], A.extend([0]) and A.extend([0,1]) will give me A=[0,0,1]. Probably the callback works in a different way. So my question is how to get A=[0,0,1] instead of [[0],[0,1]]? Thank you in advance for any comments.


回答1:


Callback is called once with the result ([[0], [0, 1]]) if you use 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]]

Use apply_async if you want callback to be called for each time.

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()


来源:https://stackoverflow.com/questions/19699165/how-does-the-callback-function-work-in-python-multiprocessing-map-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!