2014-04-13 3 views
2

나는 파이썬에서 멀티 프로세싱 모듈을 배우려고 노력하고있어 나는이 코드를 작성했습니다 :파이썬 멀티 문제

from multiprocessing import Process,Queue 
import itertools 

alphabet = 'abcdefghijklmnopqrstuvwxyz' 
max_length = 4 
num_procs = 8 
procs = [] 

#Function to get the combinations..Eg: if the chunk is abc: 
#The combinations should be a, aa, ab,... abc, abcd, ....., b, ba,bb..... 
def doSomething(inp_chunk,q): 
    for letter in inp_chunk: 
     for i in range(max_length-1): 
      for c in itertools.combinations(alphabet,i): 
       word = letter + ''.join(c) 
       q.put(word) 



def main(): 
    #Divide the alphabet in to chunks based on number of processes 
    chunk_size = int(len(alphabet)/num_procs) 


    q = Queue() 

    #Start Processes and assign chunk of characters to each 
    for i in range(num_procs): 
     if i == num_procs-1: 
      p = Process(target=doSomething,args=(alphabet[i*chunk_size:],q,)) 
     else:  
      p = Process(target=doSomething,args=(alphabet[i*chunk_size:(i*chunk_size)+chunk_size],q,)) 
     procs.append(p) 
     p.start() 

    #Join the processes  
    for p in procs: 
     p.join() 

    print q.get() 


if __name__=='__main__': 
    main() 

을하지만 어떤 이유로이 작동하지 않습니다. q.get의 인쇄 문()는

를 출력하고 프로세스가 계속 실행. 그러나 다중 루프없이 코드를 실행했을 때 for 루프의 프로세스 대신 함수를 호출하면 작동하여 출력을 보냈습니다. 그리고 그것은 약 1 초 정도 걸렸습니다.

여기서 내가 뭘 잘못하고 있니? 감사합니다. .

+3

대기열의 첫 번째 요소 만 가져옵니다. queue.get이 비어있을 때까지 반복하여 포장하십시오. – Dean

+0

@Dean 감사합니다! 그거였다. Empty 예외를 위반하는 while 루프를 추가하고 조합을 인쇄합니다. 그러나 프로그램이 종료되지 않는 것처럼 보이고 조인을 사용하고있을 때에도 그대로 있습니다. 이게 왜 그렇게? 내가 해결할 수 있도록 대답으로 게시 할 수 있습니까? – rahules

답변

0

이 명령은 한번만 실행되고 :

큐에 넣어 첫 번째 문자를 검색하고 인쇄 할 수 있다는 것을 의미
print q.get() 

. 문자의 나머지 얻기 위해 루프에서이 문장을 넣어 : 당신이 q.get()에 대한 호출에 차단받을 염려되는 경우

while not q.empty(): 
    print q.get() 

을,이 시도 :

while not q.empty(): 
    try: 
     print q.get(block=False) 
    except Queue.Empty: 
     break 

The docs for Queue 상태가 아닌 것을 차단 전화가 Queue.get() 일 경우 예외가 발생할 수 있습니다. Queue.empty()False 인 경우에도 예외를 catch해야합니다.