33

コードをデバッグするのに一晩かかりましたが、ついにこのトリッキーな問題を発見しました。以下のコードを見てください。

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]]です ?

4

1 に答える 1

45

[[0], [0, 1]]map_async を使用する場合、コールバックは結果 ( ) で 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()
于 2013-10-31T05:55:17.877 に答える