2014-11-01 3 views
1

스레딩에 익숙하다. 기존 응용 프로그램에서 스레딩을 사용하여 좀 더 빠르게 만들고 싶습니다.파이썬 스레딩 반환 값

나는 주 Dict로 돌아가서 이것을 별도 스레드로 보내어 한 번에 하나가 아닌 동시에 실행되도록하는 몇 가지 기능을 가지고있다.

나는 약간의 인터넷 검색을 수행했지만 내 기존 코드에 맞는 무언가를 찾는 것처럼 보이고 약간의 도움이 될 수 있습니다.

parsed['cryptomaps'] = pipes.ConfigParse.crypto(parsed['split-config'], parsed['asax'], parsed['names']) 

여기서 문제는 반환 값입니다 :

나는 주위에 여섯 같은 주요 DICT로 돌아가 기능을 가지고 있습니다. 나는 이것을 위해 큐를 사용할 필요가 있다는 것을 이해하지만이 6 개의 함수 각각에 대한 큐 또는 이들 모두를위한 하나의 큐를 필요로 할 것입니다. 나중에 어떻게하면 스레드에서 리턴을 분리하고 올바른 Dict 항목에 할당 할 수 있습니까?

위의 사항에 대한 도움이 될 것입니다.

답변

1

당신은의 튜플 (노동자, 데이터)를 밀어 수있는 소스를 식별하기 위해 대기한다. 글로벌 인터프리터 (Global Interpreter Lock)로 인해 파이썬 스레딩은별로 유용하지 않습니다. 멀티 스레딩과 매우 유사한 인터페이스를 제공하지만 실제로 작업자의 수에 따라 확장되는 멀티 프로세싱 모듈을 살펴 보는 것이 좋습니다.

편집 :

코드 샘플.

import multiprocessing as mp 

# py 3 compatibility 
try: 
    from future_builtins import range, map 
except ImportError: 
    pass 


data = [ 
    # input data 
    # {split_config: ... } 
] 

def crypto(split_config, asax, names): 
    # your code here 
    pass 

if __name__ == "__main__": 
    terminate = mp.Event() 
    input = mp.Queue() 
    output = mp.Queue() 


    def worker(id, terminate, input, output): 
     # use event here to graciously exit 
     # using Process.terminate would leave queues 
     # in undefined state 
     while not terminate.is_set(): 
      try: 
       x = input.get(True, timeout=1000) 
       output.put((id, crypto(**x))) 
      except Queue.Empty: 
       pass 

    workers = [mp.Process(target=worker, args=(i,)) for i in range(0, mp.cpu_count())] 
    for worker in workers: 
     worker.start() 

    for x in data: 
     input.put(x) 

    # terminate workers 
    terminate.set() 

    # process results 
    # make sure that queues are emptied otherwise Process.join can deadlock 

    for worker in workers: 
     worker.join()