How does the callback function work in multiprocessing map_async?

后端 未结 1 963
天命终不由人
天命终不由人 2020-12-08 01:02

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

d         


        
相关标签:
1条回答
  • 2020-12-08 02:00

    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()
    
    0 讨论(0)
提交回复
热议问题