Python Concurrent Futures - ThreadPoolExecutor & ProcessPoolExecutor
concurrent.futures 모듈은 파이썬에서 병렬 작업을 간소화하며, ThreadPoolExecutor와 ProcessPoolExecutor 두 가지 주요 클래스를 제공합니다. 🚀
ThreadPoolExecutor는 스레드를 사용하여 I/O 바운드 작업(네트워크 요청, 파일 I/O 등)에 적합하며, 대기 시간 동안 GIL을 해제하여 병렬 처리를 가능하게 합니다. 🌐
ProcessPoolExecutor는 별도의 프로세스를 사용하여 CPU 바운드 작업(수치 계산, 이미지/비디오 처리 등)에 적합하며, GIL의 제약을 우회하여 진정한 병렬 실행을 가능하게 합니다. 🧠
- 파이썬의 GIL(Global Interpreter Lock)은 한 번에 하나의 스레드만 실행되도록 제한하므로, CPU 바운드 작업에는
ThreadPoolExecutor가 성능 향상에 도움이 되지 않습니다. 🔒
- 실제 예시에서
sum_of_squares와 같은 CPU 바운드 작업은 ProcessPoolExecutor를 통해 11초에서 4초로 크게 단축되었습니다. ⚡
- 반면,
fetch_URL과 같은 I/O 바운드 작업은 ThreadPoolExecutor를 통해 15초에서 3초로 대폭 빨라졌습니다. ⏱️
executor.map() 함수는 여러 입력에 대해 동일한 함수를 병렬로 적용하는 간편한 방법을 제공하며, with 문을 사용하여 Executor를 안전하게 관리하는 것이 권장됩니다. 🗺️
데브허브 | DEVHUB | Python Concurrent Futures - ThreadPoolExecutor & ProcessPoolExecutor