PYTHON · 비동기
동시성 제한 (Semaphore)
asyncio.Semaphore로 동시 실행 수를 제한하여 리소스를 보호합니다.
비동기중급Semaphore세마포어동시성제한
핵심 설명
asyncio.Semaphore로 동시 실행 수를 제한하여 리소스를 보호합니다.
Python code
import asyncio
import time
async def limited_task(sem: asyncio.Semaphore, task_id: int):
async with sem:
print(f" 시작 Task-{task_id} (t={time.perf_counter():.1f})")
await asyncio.sleep(1) # 작업 시뮬레이션
print(f" 완료 Task-{task_id}")
return task_id
async def main():
sem = asyncio.Semaphore(3) # 최대 3개 동시 실행
start = time.perf_counter()
tasks = [limited_task(sem, i) for i in range(9)]
results = await asyncio.gather(*tasks)
elapsed = time.perf_counter() - start
print(f"결과: {results}")
print(f"소요: {elapsed:.1f}초") # 약 3초 (3배치 × 1초)
# BoundedSemaphore: 릴리스 횟수 초과 방지
bounded = asyncio.BoundedSemaphore(2)
async with bounded:
print("BoundedSemaphore 사용")
# bounded.release() # ValueError! (acquire 없이 release)
asyncio.run(main())학습 팁
API 호출 시 Rate Limiting을 구현할 때 Semaphore가 유용합니다.
주의할 점
Semaphore는 release()를 초과 호출해도 에러가 발생하지 않습니다. 안전하게 사용하려면 BoundedSemaphore를 사용하세요.
자주 묻는 질문
동시성 제한 (Semaphore)란 무엇인가요?
asyncio.Semaphore 로 동시 실행 수를 제한하여 리소스를 보호합니다.
동시성 제한 (Semaphore) 학습 시 주의할 점은 무엇인가요?
Semaphore 는 release() 를 초과 호출해도 에러가 발생하지 않습니다. 안전하게 사용하려면 BoundedSemaphore 를 사용하세요.