2014-11-09 2 views
0

저는 오늘 파이썬에서 멀티 프로세싱과 관련하여 머리를 날카롭게하고 있습니다. 조금 더 진전을 이루었습니다. 질문이 중복되거나 내 무지가 분명하다면 사과드립니다. 이런 식으로 다른 곳에서 물어보십시오.다중 처리 및 변수 반환?

나는 병렬로 함수를 실행하는 방법을 찾고 있으며, 그들이 제작 한 임의의 것을 메인 스크립트로 반환한다.

질문 : 다중 프로세스에서 시작된 Process()가 목록 또는 기타 임의의 변수 유형을 반환 할 수 있습니까?

def 30_second_function(): 
    #pretend this takes 30 seconds to run 
    return ["mango", "habanero", "salsa"] 
#End 30_second_function() 

def 5_second_function(): 
    #pretend this takes 5 seconds to run 
    return {"beans": "8 oz", "tomato paste": "16 oz"} 
#End 5_second_function() 

p1 = multiprocessing.Process(target=30_second_function) 
p1.start() 
p2 = multiprocessing.Process(target=5_second_function) 
p2.start() 

#Somehow retrieve the list and the dictionary here. p1.returned?? 

을 그리고 어떻게 든 30_second_function에서 목록 및 5_second_function에서 사전에 액세스 :

예를 들어, 나는 싶습니다. 이것이 가능한가? 내가 잘못된 방향으로가는거야?

답변

3

Process 자체는 반환 값을 가져 오는 방법을 제공하지 않습니다. To exchange data between processes, you need to use queue, pipe, 공유 메모리, ... :

import multiprocessing 

def thirty_second_function(q): 
    q.put(["mango", "habanero", "salsa"]) 

def five_second_function(q): 
    q.put({"beans": "8 oz", "tomato paste": "16 oz"}) 

if __name__ == '__main__': 
    q1 = multiprocessing.Queue() 
    p1 = multiprocessing.Process(target=thirty_second_function, args=(q1,)) 
    p1.start() 

    q2 = multiprocessing.Queue() 
    p2 = multiprocessing.Process(target=five_second_function, args=(q2,)) 
    p2.start() 

    print(q1.get()) 
    print(q2.get()) 

대체 multiprocessing.pool.Pool 사용 : concurrent.futures module (also available in standard library since Python 3.2+를)

import multiprocessing.pool 

def thirty_second_function(): 
    return ["mango", "habanero", "salsa"] 

def five_second_function(): 
    return {"beans": "8 oz", "tomato paste": "16 oz"} 

if __name__ == '__main__': 
    p = multiprocessing.pool.Pool() 
    p1 = p.apply_async(thirty_second_function) 
    p2 = p.apply_async(five_second_function) 

    print(p1.get()) 
    print(p2.get()) 

또는 사용 :

from concurrent.futures import ProcessPoolExecutor 

def thirty_second_function(): 
    return ["mango", "habanero", "salsa"] 

def five_second_function(): 
    return {"beans": "8 oz", "tomato paste": "16 oz"} 

if __name__ == '__main__': 
    with ProcessPoolExecutor() as e: 
     p1 = e.submit(thirty_second_function) 
     p2 = e.submit(five_second_function) 
    print(p1.result()) 
    print(p2.result()) 
+0

이 내가 필요 정확히 - 난 왜 내가 이것을 문서에서 이해하지 못했는지 모르겠다. 그러나 여기서 당신의 예가 실제로 도움이되었다. 나는 그것을 시도하기를 기다릴 수 없다. 주제 끄기 - 왜 args = (q1,)이 제대로 작동하지 않는 것 같은 겉보기 쉼표가 필요한지 아십니까? – Locane

+1

@Locane, 후행 쉼표없이 'q1'과 동일한'(q1)'을 실행하십시오. 목록 양식 대신'[q1]'을 사용할 수 있습니다. – falsetru

+1

@Locane, 네가 맞아. 뒤에 오는 쉼표는 그것을 나타 내기 위해 거기에 있으며, 그것은 튜플 리터럴입니다. BTW, 그것은 또한 목록을 받아들입니다. – falsetru