반응형
내 코드를 디버그하는 데 밤새도록 비용이 들었고 마침내이 까다로운 문제를 발견했습니다. 아래 코드를 살펴보세요.
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
반응형
'파이썬' 카테고리의 다른 글
파이썬의 열거 형 (0) | 2021.01.03 |
---|---|
파이썬 Python 오류 : "지정된 경로를 찾을 수 없습니다" (0) | 2021.01.03 |
파이썬 "for line in ..."결과 UnicodeDecodeError : 'utf-8'코덱이 바이트를 디코딩 할 수 없습니다. (0) | 2021.01.03 |
파이썬 Center-/middle-align text with PIL? (0) | 2021.01.03 |
파이썬 Pandas 데이터 프레임 / 시리즈 데이터를 그림으로 저장하는 방법은 무엇입니까? (0) | 2021.01.03 |
댓글