PHpullh
학습 라이브러리/Python/asyncio — async/await 기초

PYTHON · 비동기

asyncio — async/await 기초

Python의 비동기 I/O 라이브러리. 코루틴으로 I/O 대기 시간을 효율적으로 활용합니다.

비동기중급asyncioasyncawaitgathercreate_task

핵심 설명

Python의 비동기 I/O 라이브러리. 코루틴으로 I/O 대기 시간을 효율적으로 활용합니다.

Python code

import asyncio
import time

# 기본 코루틴
async def fetch_data(url: str, delay: float) -> str:
    print(f"시작: {url}")
    await asyncio.sleep(delay)   # 비차단 대기
    print(f"완료: {url}")
    return f"data:{url}"

# asyncio.gather — 병렬 실행
async def main_parallel():
    start = time.perf_counter()

    results = await asyncio.gather(
        fetch_data("url1", 1.0),
        fetch_data("url2", 1.5),
        fetch_data("url3", 0.5),
    )

    elapsed = time.perf_counter() - start
    print(f"총 소요: {elapsed:.2f}초")   # ~1.5초 (병렬)
    print(results)

# asyncio.create_task — 태스크 생성
async def main_tasks():
    task1 = asyncio.create_task(fetch_data("a", 1.0))
    task2 = asyncio.create_task(fetch_data("b", 0.5))

    # 여기서 다른 작업 가능
    print("태스크 생성 후 바로 실행 가능")

    r1 = await task1
    r2 = await task2
    return r1, r2

# 타임아웃
async def with_timeout():
    try:
        result = await asyncio.wait_for(
            fetch_data("slow", 5.0),
            timeout=2.0
        )
    except asyncio.TimeoutError:
        print("타임아웃!")

asyncio.run(main_parallel())

학습 팁

asyncio.gather()는 모두 완료될 때까지 기다리고, asyncio.create_task()는 즉시 스케줄링합니다. 태스크는 await 없어도 백그라운드에서 실행됩니다.

주의할 점

time.sleep()은 전체 이벤트 루프를 차단합니다. async 함수 안에서는 반드시 await asyncio.sleep()을 사용하세요.

자주 묻는 질문

asyncio — async/await 기초란 무엇인가요?

Python의 비동기 I/O 라이브러리. 코루틴으로 I/O 대기 시간을 효율적으로 활용합니다.

asyncio — async/await 기초 학습 시 주의할 점은 무엇인가요?

time.sleep() 은 전체 이벤트 루프를 차단합니다. async 함수 안에서는 반드시 await asyncio.sleep() 을 사용하세요.