본문 바로가기
파이썬

파이썬 다중 처리 map_async에서 콜백 함수는 어떻게 작동합니까?

by º기록 2021. 1. 3.
반응형

내 코드를 디버그하는 데 밤새도록 비용이 들었고 마침내이 까다로운 문제를 발견했습니다. 아래 코드를 살펴보세요.

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] 을 제공합니다. 아마도 콜백은 다른 방식으로 작동합니다. 제 질문은 [[0], [0,1]] 대신 A = [0,0,1] 을 얻는 방법입니다.

 

해결 방법

 

map_async를 사용하면 콜백이 결과 ( [[0], [0, 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]]


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()

 

참조 페이지 https://stackoverflow.com/questions/19699165

 

 

반응형

댓글