2017-02-28 3 views
0

나는 Python multiprocessing.Pool: when to use apply, apply_async or map?을 읽었지만 유용했지만 여전히 내 자신의 질문이있었습니다. 다음 코드에서는 result_list.append (result)를 병렬로 사용하기 위해 4 개의 프로세서가 결과를 병렬로 추가하고 4 개의 목록을 1 개의 목록으로 변환하도록합니다.Python 다중 처리 .Pool : 병렬로 reasults에 참여하는 방법은 무엇입니까?

import multiprocessing as mp 
import time 

def foo_pool(x): 
    time.sleep(2) 
    return x*x 

result_list = [] 
def log_result(result): 
    # This is called whenever foo_pool(i) returns a result. 
    # result_list is modified only by the main process, not the pool workers. 
    result_list.append(result) 

def apply_async_with_callback(): 
    pool = mp.Pool(4) 
    for i in range(10): 
     pool.apply_async(foo_pool, args = (i,), callback = log_result) 
    pool.close() 
    pool.join() 
    print(result_list) 

if __name__ == '__main__': 
    apply_async_with_callback() 
+0

4 개의 프로세서가있는 4 개의 목록을 생성하고 나중에 4 개의 목록을 1 개의 목록에 병합하는 것이 더 쉽습니까? –

+0

그게 정확히 내가 원하는, 그것을 구현하는 방법은 무엇입니까? – shao

+1

나는 당신이 무엇을 요구하고 있는지 잘 모르겠습니다. 당신이'pool.map'을 원한 것처럼 들립니다. 목록이 주 프로세스의 메모리 (다른 프로세스와 공유되지 않음)에 있으므로 자식 프로세스가 결과 목록에 추가 작업을 수행 할 방법이 없습니다. 약간의 노력 (예 :'multiprocessing.Array')으로 작동 할 수있는 동기화 된 유형이 있지만 안전하게 사용하려면 오버 헤드가 많이 필요할 것입니다. 'pool.map'을 사용하는 것은 훨씬 쉬우 며 비슷한 시스템을 사용하는 것보다 빠릅니다. – Blckknght

답변

1

Multiprocessing pool이 선택됩니다.

다음은 몇 가지 샘플 코드입니다. 도움이되기를 바랍니다. 내 대답을 확인하여 자세한 내용을 볼 수도 있습니다. How can I make my python code run faster

from multiprocessing import Pool 
    import time 

    def foo_pool(x): 
     return x*x 

    def main(): 
     pool = Pool(4) 
     sampleData = [x for x in range(9)] 
     results = pool.map(foo_pool, sampleData) 
     pool.close() 
     pool.join() 
     print(results) 

    if __name__ == '__main__': 
     main()