2017-04-13 8 views
0

방금 ​​파이썬 다중 처리를 배웠습니다. 네트워크에서 메시지를 보내고받는 과정을 시뮬레이션하는 모델을 만들고 싶습니다. 유향 그래프는 두 노드 간의 관계를 설명하고 사전은 두 노드 간의 통신을 설명합니다. 이 사전 값의 데이터 유형은 대기열입니다. 하지만 약간의 오차가 충족 : 멀티 프로세싱에서 공유 dict()의 파이썬 공유 대기열()

from concurrent.futures import ProcessPoolExecutor 
from multiprocessing import Manager 

PoolGroup=[('R1','R2','R3'),('N1','N2','N3'),('E1','E2','E3')] 
PoolElement=['R1','R2','R3','N1','N2','N3','E1','E2','E3'] 
graph={'R1':['N1','N2','N3'], 
    'R2':['N1','N2','N3'], 
    'R3':['N1','N2','N3'], 
    'N1':['E1','E2','E3'], 
    'N2':['E1','E2','E3'], 
    'N3':['E1','E2','E3'], 
    'E1':[], 
    'E2':[], 
    'E3':[]} 

def addSigal(target,information): 
    AllQueue[target].put(information) 
    print("Succeed in sending msg to "+target) 
    print(target+' now has ',AllQueue[target].qsize(),' signals') 


def pool1function(name,information): 
    targetlist=list(graph[name]) 
    print(name+" send information to "+str(targetlist))    
    with ProcessPoolExecutor() as pool1: 
     pool1.map(addSigal,targetlist,[information]*3) 


if __name__=='__main__': 
    m=Manager() 
    AllQueue=m.dict() 
    AllQueue.update({PE:m.Queue() for PE in PoolElement}) 
    with ProcessPoolExecutor() as pool:  
     pool.map(pool1function,PoolGroup[0],[1,2,3]) 

불행하게도, 결과는 단지 보여 주었다 :

R1 send information to ['N1', 'N2', 'N3'] 
R2 send information to ['N1', 'N2', 'N3'] 
R3 send information to ['N1', 'N2', 'N3'] 

는이 정보를 해당 노드로 전송되지 않습니다 것을 의미합니다. 그래서 AllQueue을 확인하고 이상한 뭔가를 발견 : 나는 AllQueue [ 'R1'을] 인쇄 할 때, 그것은 보여 주었다 :

RemoteError: 
--------------------------------------------------------------------------- 
Unserializable message: ('#RETURN', <queue.Queue object at 0x10edd8dd8>) 
--------------------------------------------------------------------------- 

나는 또한 문제가 무엇을 넣어 또는 AllQueue [ 'R1']에서 요소를 가져 오지 못했습니다?

from concurrent.futures import ProcessPoolExecutor 
from multiprocessing import Manager 


def addSigal(target, information, q): 
    print(target,information,q) 
    q[target]=(information) 
    print("Succeed in sending msg to "+target) 
    print(target+' now has ',q[target]) 


if __name__=='__main__': 
    m = Manager() 
    AllQueue = m.dict() 
    AllQueue.update({'A':0,'B':1}) 
    with ProcessPoolExecutor() as pool: 
     pool.map(addSigal,'AB', [1, 2],[AllQueue,AllQueue]) 
    print(AllQueue) 
+0

내가 AllQueue'가 정의'모르겠어요 : – quamrana

+0

AllQueue의 정의를 메인에서 빼내려고했거나 글로벌 변수로 만들려고했는데 결과는 같았습니다 ... – Coneain

+0

'ProcessPoolExecutor' 또는'multiprocessing.Pool'을 사용할 때 AllQueue가 범위를 벗어난 것처럼 보입니다. 'map' 호출을 통해'AllQueue'를 매개 변수로 전달해야합니다. – quamrana

답변

0

는 작업에 사전 전달의 예입니다. 또한 중복 요소를 제거하기 위해 질문을 편집하십시오 : 모든 수입이 필요합니까?
+0

네, 맞습니다. 이것은 일대일 방식으로 작동하지만 일대일 방식은 어떻습니까? 하나는 하나의 숫자가 아니라 숫자의 순서를받습니다. 사전의 가치는 단지 하나의 숫자입니다, 나는 그것이 충분하지 않다고 두려워합니다 ... – Coneain

+0

글쎄, 나는이 문제에 대해 당신이 생각하는 것 같습니다. 필자는 주요한 문제는 각기 다른 프로세스가 자체적으로 변수 복사본을 가지고 있으며 해결 방법은 매개 변수로 전역 변수를 보내는 것입니다. 당신은 이것으로 계속 지낼 필요가 있습니다. – quamrana

+0

좋아, 그게 핵심이야! 알았다. 감사! – Coneain