How does the callback function work in multiprocessing map_async?(回调函数在多处理 map_async 中如何工作?)
问题描述
调试代码花了我一晚上的时间,终于发现了这个棘手的问题.请看下面的代码.
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()
我以为我会得到 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]]?
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]]?
推荐答案
如果使用 map_async,则调用一次回调并返回结果 ([[0], [0, 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]]
使用 apply_async如果您希望每次都调用回调.
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()
这篇关于回调函数在多处理 map_async 中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:回调函数在多处理 map_async 中如何工作?
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
