6

を使用すると、コールバックが機能しないようですmap_async()。少し変更したコードを使用して、apply_async()代わりにタスクを追加する配列をループすると機能します。ドキュメントから、コールバックを で使用できるはずですがmap_async()、おそらくそれはある種の初心者の間違いです...

from multiprocessing import Pool,TimeoutError
from time import sleep

servers=["s1","s2","s3","s4","s5","s6"]

def f(x):
    print("start f(" + x + ")")
    sleep(5)
    print("end   f(" + x + ")")
    return "did " + x

def mycallback(x):
    print("My callback " + str(x))

def myerrorcallback(r):
    print("My errorcallback " + str(r))

if __name__ == '__main__':
    pool = Pool(processes=4)
    results = pool.map_async(f, servers,  chunksize=1, callback=mycallback, error_callback=myerrorcallback)
    print(results.get(timeout=11))

実行すると、次のようになります。

D:\python> f.py
start f(s1)
start f(s2)
start f(s3)
start f(s4)
end   f(s1)
start f(s5)
end   f(s2)
start f(s6)
end   f(s4)
end   f(s3)
end   f(s5)
end   f(s6)
['did s1', 'did s2', 'did s3', 'did s4', 'did s5', 'did s6']

代わりに変更されたコードを使用するとapply_async()、コールバックから印刷出力が得られます。変更されたコードは、最後の部分を次のように変更するだけです。

if __name__ == '__main__':
    pool = Pool(processes=4)
    for server in servers:
        pool.apply_async(f, (server,),  callback=mycallback, error_callback=myerrorcallback)
    pool.close()
    pool.join()

結果:

D:\python\>fb.py
start f(s1)
start f(s2)
start f(s3)
start f(s4)
end   f(s1)
start f(s5)
My callback did s1
end   f(s2)
My callback did s2
start f(s6)
end   f(s3)
My callback did s3
end   f(s4)
My callback did s4
end   f(s5)
My callback did s5
end   f(s6)
My callback did s6
4

1 に答える 1

3

OK、私はチャンスをつかみ、バグを記録しました。これは実際には 3.3 のバグであり、パッチが進行中です。

http://bugs.python.org/issue16307

于 2012-10-24T22:14:49.313 に答える