728x90
반응형
- 개요
concurrent.futures 모듈에서 동시성과 병렬성을 구현하는 방법은 다음과 같다
- ThreadPoolExecutor : 여러개의 스레드를 사용
- 여러개의 스레드를 전환하며 작업을 진행하므로 동시성(Concurrency)을 구현함
- 스레드들은 GIL에 의해 영향을 받아 병렬처리가 불가능
- 파일 작업이나 네트워크 작업과 같은 I/O 작업에서는 GIL이 해제되므로 유리함
- ProcessPoolExecutor : 여러개의 프로세스를 사용
- 여러개의 프로세스를 생성하여 작업을 진행하므로 병렬성(Parallelism)을 구현함
- 프로세스들은 자신만의 GIL을 가지므로 영향을 받지 않아 병렬처리가 가능
- 인공지능이나 빅데이터와 같은 대규모 데이터 처리를 진행하는 CPU 바운드 작업에서 유리함
- 예제
import time
from concurrent import futures
JOBS = [1000, 10000, 100000, 1000000]
def sum_generator(n):
return sum(n for n in range(1, n + 1))
...
ThreadPoolExecutor와 ProcessPoolExecutor를 사용하여 위의 sum_generator 함수를 수행한다
1부터 1000 / 1부터 10000 / 1부터 10000 / 1부터 100000까지의 합을 구하여 반환한다
1) ThreadPoolExecutor의 사용
...
def UseThreadPool():
# 작업 시작 시간
start_tm = time.time()
# ThreadPool 사용
with futures.ThreadPoolExecutor() as excutor:
result = excutor.map(sum_generator, JOBS)
# 작업 종료 시간
end_tm = time.time() - start_tm
# 최종 작업 수행 시간 출력
print(f"Result = {list(result)} / Time : {end_tm:.2f}")
if __name__ == '__main__':
UseThreadPool()
위와 같이 코드를 구성하였다
ThreadPoolExecutor를 사용하여 JOBS에 대한 작업을 수행하고 전체 작업 시간을 반환한다
이때 map 함수를 사용하여 JOBS를 순회하면서 sum_generator 함수를 수행한다

ThreadPoolExecutor을 통해 작업한 시간은 위와 같다
2) ProcessPoolExecutor의 사용
...
def UseProcessPool():
# 작업 시작 시간
start_tm = time.time()
# ProcessPool 사용
with futures.ProcessPoolExecutor() as excutor:
result = excutor.map(sum_generator, JOBS)
# 작업 종료 시간
end_tm = time.time() - start_tm
# 최종 작업 수행 시간 출력
print(f"Result = {list(result)} / Time : {end_tm:.2f}")
# 실행
if __name__ == '__main__':
UseProcessPool()
위와 같이 코드를 구성하였다
ProcessPoolExecutor를 사용하여 JOBS에 대한 작업을 수행하고 전체 작업 시간을 반환한다
동일하게 map 함수를 사용하여 순회하면서 작업을 진행한다

ProcessPoolExecutor를 통해 작업한 시간은 위와 같다
728x90
반응형
'Python > 파이썬 심화' 카테고리의 다른 글
| AsyncIO 라이브러리 (0) | 2025.11.01 |
|---|---|
| Futures 모듈 (2) (0) | 2025.10.25 |
| Futures 모듈이란? (0) | 2025.10.19 |
| 코루틴 (2) (0) | 2025.10.12 |
| 코루틴 (1) (0) | 2025.10.12 |