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 패키지의 spawn 모드로 동작하는 uvicorn의 workers

지난 글에서 multiprocessing 패키지의 Pool 사용을 알아봤는데요,

파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)
; https://www.sysnet.pe.kr/2/0/13874

이번에는 uvicorn에서의 multiprocessing 처리를 다뤄보겠습니다. 우선, 테스트를 위해 다음과 같은 main.py 파일을 만들고,

import time
import datetime
import os

import uvicorn
from fastapi import FastAPI

g_var = 0

app = FastAPI()
print(f"main.py with {g_var} at {os.getpid()}")

g_var += 1


@app.get('/')
def home():
    global g_var
    output = f"started = {datetime.datetime.now()}, end = "
    time.sleep(10)
    output += f"{datetime.datetime.now()}, Hello {os.getpid()}, g_var = {g_var}"
    return output


if __name__ == "__main__":
    uvicorn.run("main:app", workers=3, host="0.0.0.0", port=8000, reload=False)

실행하면 workers=3으로 인해 다음과 같은 식으로 출력이 나옵니다.

$ python3 main.py
main.py with 0 at 2585362:139999625058112 - 
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started parent process [2585362]
main.py with 0 at 2585367:140270000273216 - <fastapi.applications.FastAPI object at 0x7f93269bdd60>
main.py with 0 at 2585366:139725771581248 - <fastapi.applications.FastAPI object at 0x7f14700d0d60>
main.py with 0 at 2585365:139681518356288 - <fastapi.applications.FastAPI object at 0x7f0a225a6d60>
main.py with 0 at 2585367:140270000273216 - <fastapi.applications.FastAPI object at 0x7f9324cdad30>
INFO:     Started server process [2585367]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
main.py with 0 at 2585366:139725771581248 - <fastapi.applications.FastAPI object at 0x7f146e3edd30>
INFO:     Started server process [2585366]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
main.py with 0 at 2585365:139681518356288 - <fastapi.applications.FastAPI object at 0x7f0a208c3d30>
INFO:     Started server process [2585365]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

잘 보시면, 프로세스 1개의 동일한 스레드에서 FastAPI 개체가 2개씩 생성되는데, 즉, 1개의 프로세스에서 2개의 main.py 인스턴스를 로드하고 있는 것입니다. 또한 이때의 프로세스 구조를 보면,

$ pstree -ap $(pgrep python3 | head -n 1)
python3,2585362 main.py
  ├─python3,2585364 -c from multiprocessing.resource_tracker import main;main(4)
  ├─python3,2585365 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=7) --multiprocessing-fork
  ├─python3,2585366 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=9) --multiprocessing-fork
  └─python3,2585367 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11) --multiprocessing-fork

uvicorn이 내부적으로 multiprocessing 패키지를 그대로 이용하고 있음을 짐작게 합니다. 재미있는 것은, 리눅스에서도 spawn_main으로 프로세스가 생성되기 때문에 fork 방식이 아니므로 출력에서 g_var 값이 증감 없이 "0"으로 나옵니다. (얼핏 명령행에 "--multiprocessing-fork"라고 돼 있어 fork 방식으로 보일 수 있지만, 실제로는 spawn 방식입니다.)




workers == 3이고, main.py는 각 프로세스 당 2개씩 생성되었는데 이것은 이후 요청의 분배에 따라 상황이 바뀝니다. 그래서 이래저래 요청을 보내다가 어느 순간 프로세스 구조를 보면 이런 식으로 바뀐 것을 볼 수 있습니다.

$ pstree -ap $(pgrep python3 | head -n 1)
python3,2585362 main.py
  ├─python3,2585364 -c from multiprocessing.resource_tracker import main;main(4)
  ├─python3,2585365 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=7) --multiprocessing-fork
  │   ├─{python3},2590355
  │   ├─{python3},2591017
  │   └─{python3},2591018
  ├─python3,2585366 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=9) --multiprocessing-fork
  │   └─{python3},2587767
  └─python3,2585367 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11) --multiprocessing-fork

출력에도 나오듯이 2585365 프로세스에서 3개의 스레드가 생성됐는데요, 이런 상태에서 클라이언트 3개가 요청을 보내면 모두 2585365 프로세스로 전달돼 처리가 됩니다. (물론, 상황에 따라 달라질 수 있습니다.)

참고로, workers=1로 설정하면 resource_tracker 및 자식 프로세스 없이 원래의 프로세스가 요청 처리를 담당합니다.

// workers를 지정하지 않은 경우, 기본값은 1
// uvicorn.run("main:app", workers=1, host="0.0.0.0", port=8000, reload=False)

$ pstree -ap $(pgrep python3 | head -n 1)
python3,2600344 main.py
  ├─{python3},2600346
  ├─{python3},2600347
  ├─{python3},2600348
  ├─{python3},2600349
  ├─{python3},2600535
  └─{python3},2600566

// uvicorn.run("main:app", workers=2, host="0.0.0.0", port=8000, reload=False)

$ pstree -ap $(pgrep python3 | head -n 1)
python3,2601302 main.py
  ├─python3,2601304 -c from multiprocessing.resource_tracker import main;main(4)
  ├─python3,2601305 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=7) --multiprocessing-fork
  └─python3,2601306 -c from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=9) --multiprocessing-fork




혹시 uvicorn의 자식 프로세스를 spawn이 아닌 fork로 지정할 수 있을까요? 검색 실력이 없어서 그런지 모르겠지만, 일단 제가 찾아본 바로는 그런 옵션이 없습니다. 대신 gunicorn의 경우에는 오히려 기본 방식이 fork라고 합니다.

따라서, fork로 강제하고 싶다면 uvicorn이 아닌 gunicorn으로 호스팅 방식을 바꿔야 할 것입니다. 그러고 보면, 이런 기본 방식의 차이점 때문에 uvicorn은 윈도우에서도 돌아가고, gunicorn은 윈도우 지원을 못 하는 듯합니다.




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







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

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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  [114]  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11107정성태11/9/201626252오류 유형: 371. Post cache substitution is not compatible with modules in the IIS integrated pipeline that modify the response buffers.파일 다운로드1
11106정성태11/8/201626512.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제 [2]파일 다운로드1
11105정성태11/8/201621000.NET Framework: 622. PeerFinder Wi-Fi Direct 통신 시 Read/Write/Dispose 문제
11104정성태11/8/201619890개발 환경 구성: 305. PeerFinder로 Wi-Fi Direct 연결 시 방화벽 문제
11103정성태11/8/201620411오류 유형: 370. PeerFinder.ConnectAsync의 결과 값인 Task.Result를 호출할 때 System.AggregateException 예외 발생
11102정성태11/8/201620446오류 유형: 369. PeerFinder.FindAllPeersAsync 호출 시 System.UnauthorizedAccessException 예외 발생
11101정성태11/8/201622660.NET Framework: 621. 닷넷 프로파일러의 오류 코드 - 0x80131363
11100정성태11/7/201630278개발 환경 구성: 304. Wi-Fi Direct 지원 여부 확인 방법 [1]
11099정성태11/7/201632150.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201621407오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201624408오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201627896디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201624548.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201626195VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201626067웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201633225.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201627049VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201628605VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201628355디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201631509.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625838.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201620146오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201634969.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201622864오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201629140Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201631424.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
... 106  107  108  109  110  111  112  113  [114]  115  116  117  118  119  120  ...