Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 2개 있습니다.)
스크립트: 68. 파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)
; https://www.sysnet.pe.kr/2/0/13874

스크립트: 69. 파이썬 - multiprocessing 패키지의 spawn 모드로 동작하는 uvicorn의 workers
; https://www.sysnet.pe.kr/2/0/13875




파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)

아무래도 GIL(Global Interpreter Lock)의 영향으로 multiprocessing 패키지를 쓰게 될 수 있는데요,

multiprocessing — Process-based parallelism
; https://docs.python.org/3/library/multiprocessing.html

운영체제마다 프로세스를 생성하는 기본 방식이 다른 것에는 주의를 해야 합니다. 가령 아래의 소스 코드를 윈도우 버전의 파이썬에서 실행하면,

from multiprocessing import Pool

g_var = 0

def f(x):
    
    return g_var

if __name__ == '__main__':
    g_var = 5

    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

spawn으로 자식 프로세스를 생성하므로 출력이 "[0, 0, 0]"으로 나오지만, 리눅스에서 실행하면 fork 방식이기 때문에 "[5, 5, 5]"로 나옵니다. 일관성을 위해 리눅스의 경우에도 명시적으로 spawn으로 바꾸고 싶다면 이런 식으로 변경할 수 있습니다. (기본값은 파이썬 버전마다도 달라질 수 있습니다.)

from multiprocessing import Pool, get_context

g_var = 0

def f(x):
    return g_var

if __name__ == '__main__':
    g_var = 5

    # Why your multiprocessing Pool is stuck
    # https://pythonspeed.com/articles/python-multiprocessing/
    with get_context('spawn').Pool() as pool:
        print(pool.map(f, [1, 2, 3]))  # 리눅스/윈도우 - 출력 결과: [0, 0, 0]

    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))  # 리눅스 - 출력 결과: [5, 5, 5]
                                    # 윈도우 - 출력 결과: [0, 0, 0]

혹은, Pool을 사용하기 전에 set_start_method() 함수를 사용하여 전역 설정을 변경할 수도 있습니다.

from multiprocessing import Pool, get_context, set_start_method
import os

g_var = 0

def f(x):
    return g_var

if __name__ == '__main__':
    g_var = 5

    set_start_method("spawn")

    if os.name != "nt":
        with get_context('fork').Pool() as pool:  # 리눅스 - 출력 결과: [5, 5, 5]
            print(pool.map(f, [1, 2, 3]))         # 윈도우 환경에서 fork 문맥을 사용하면 "ValueError: cannot find context for 'fork'" 오류 발생

    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))  # 윈도우/리눅스 - 출력 결과: [0, 0, 0]




Pool의 경우 지정한 개수만큼 프로세스를 생성하고, map 함수에 전달한 인자를 배분하게 됩니다. 가령, 아래와 같이 코딩하면,

from multiprocessing import Pool
import time
import os

def f(x):
    return os.getpid(), x*x

if __name__ == '__main__':
    print('this process id', os.getpid())

    with Pool(5) as p:  # 윈도우 spawn, 리눅스 fork
        print(p.map(f, [1, 2, 3]))

"with Pool"의 문맥에 있는 동안은 "python" 프로세스가 총 6개(부모 프로세스 1개 + 자식 프로세스 5개)가 생성돼 있고, with 문맥을 벗어나는 순간 다시 1개로 줄어듭니다. 다시 말해, 전달한 3개의 인자 수와는 무관하게 무조건 Pool에 지정한 개수만큼 프로세스를 미리 생성하게 됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/24/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...
NoWriterDateCnt.TitleFile(s)
12835정성태9/7/202117271.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/202115412오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/202113515VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/202115534VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/202112704VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/202117029오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202118360.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/202115592.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/202115754스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202119458.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/202115619개발 환경 구성: 603. GoLand - WSL 환경과 연동
12824정성태9/2/202124856오류 유형: 760. 파이썬 tensorflow - Dst tensor is not initialized. 오류 메시지
12823정성태9/2/202114151스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
12822정성태9/1/202119211오류 유형: 759. 파이썬 tensorflow - ValueError: Shapes (...) and (...) are incompatible [2]
12821정성태9/1/202114613.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법
12820정성태9/1/202115536VC++: 147. Golang - try/catch에 대응하는 panic/recover [1]파일 다운로드1
12819정성태8/31/202116002.NET Framework: 1111. C# - FormattableString 타입
12818정성태8/31/202113866Windows: 198. 윈도우 - 작업 관리자에서 (tensorflow 등으로 인한) GPU 연산 부하 보는 방법
12817정성태8/31/202117619스크립트: 25. 파이썬 - 윈도우 환경에서 directml을 이용한 tensorflow의 AMD GPU 사용 방법
12816정성태8/30/202123327스크립트: 24. 파이썬 - tensorflow 2.6 NVidia GPU 사용 방법 [2]
12815정성태8/30/202115735개발 환경 구성: 602. WSL 2 - docker-desktop-data, docker-desktop (%LOCALAPPDATA%\Docker\wsl\data\ext4.vhdx) 파일을 다른 디렉터리로 옮기는 방법
12814정성태8/30/202120147.NET Framework: 1110. C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (DIM for Static Members) [2]파일 다운로드1
12813정성태8/29/202117238.NET Framework: 1109. C# 10 - (11) Lambda 개선파일 다운로드1
12812정성태8/28/202116570.NET Framework: 1108. C# 10 - (10) 개선된 #line 지시자
12811정성태8/27/202116446Linux: 44. 윈도우 개발자를 위한 리눅스 fork 동작 방식 설명 (파이썬 코드)
12810정성태8/27/202115449.NET Framework: 1107. .NET Core/5+에서 동적 컴파일한 C# 코드를 (Breakpoint도 활용하며) 디버깅하는 방법 - #line 지시자파일 다운로드1
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...