問題描述
調試代碼花了我一晚上的時間,終于發現了這個棘手的問題.請看下面的代碼.
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 中如何工作?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!