2017-12-07 17 views
1

for 루프를 여러 프로세스로 분해하여 계산 속도를 높이는 코드를 작성했습니다.함수 안에서 루프 내에서 루프를 다중 처리하기

import numpy as np 
import formfactors 
from subdivide_loop import subdivide_loop 
import multiprocessing 


def worker(start, end, triangleI, areaI, scene, kdtree, samples, output): 
    form_factors = np.zeros(end-start) 
    for j in range(start, end): 
     triangleJ = np.array(scene[j][0:4]) 
     form_factors[start] = formfactors.uniform(triangleJ, triangleI, areaI, kdtree, samples) 
    result = output.get(block=True) 
    for j in range(start, end): 
     result[j] = form_factors[j] 
    output.put(result) 


def calculate_formfactors(start, end, triangleI, areaI, scene, kdtree, samples, output, nb_processes, 
          max_interval_length): 
    intervals = subdivide_loop(start, end, max_interval_length, nb_processes) 
    print("start") 
    jobs = [] 
    for k in range(nb_processes): 
     p = multiprocessing.Process(target=worker, 
            args=(intervals[k][0], intervals[k][1], triangleI, areaI, scene, kdtree, 
              samples, output)) 
     jobs.append(p) 
    for p in jobs: 
     p.start() 
    for p in jobs: 
     p.join() 
    results = output.get() 
    return results 
나는이 같은 루프 내부 함수 내부 calculate_formfactors()를 호출 할 수 싶습니다

:

def outer_function(): 
    for i in range(1000): 
     for j in range(i + 1, 1000, max_interval_length): 
      form_factors = calculate_formfactors(args) 

그러나 실행이 오류 제공합니다

An attempt has been made to start a new process before the 
current process has finished its bootstrapping phase. 

This probably means that you are not using fork to start your 
child processes and you have forgotten to use the proper idiom 
in the main module: 

    if __name__ == '__main__': 
     freeze_support() 
     ... 

때문에를 외부 함수가 작동하는 방법에 대해서는 calculate_formfactors() 대신 outer_function()을 사용할 수 없습니다.

그래서 어떻게해야합니까?

답변

0

오류가 암시 하듯 __main__ 경비 (예 : __main__) 내에서 outer_function() (또는 그 시작을 시작한 곳)이 호출되는지 확인하십시오.

if __name__ == "__main__": 
    outer_function() 

그것은 outer_function() 일 필요는 없습니다하지만 당신은 다시 궁극적으로 multiprocessing.Process()에 전화로 연결 체인을 초기화하는 첫 번째 단계로 모든 것을 추적하고 위의 블록 내에서 넣어해야합니다.

이것은 포크가 아닌 시스템에서는 여러 프로세스가 본질적으로 하위 프로세스로 실행되므로 주 스크립트에서 새 프로세스를 작성하면 무한 재귀/프로세스 생성으로 끝나기 때문입니다. this answer에서 자세한 내용을 볼 수 있습니다. 따라서 다중 처리 초기화 코드가 __main__ 가드가 들어오는 위치에서 한 번만 실행되도록해야합니다.