기본 패턴
python
import asyncio
async def fetch_data():
await asyncio.sleep(0.5)
return "data"
async def main():
resulta, resultb = await asyncio.gather(fetch_data(), fetch_data())
print(resulta, resultb)
asyncio.run(main())설명
async def로 coroutine을 정의하고,await을 통해 다른 coroutine이나asyncio.sleep,aiohttp등의 awaitable을 기다립니다.asyncio.run은 최상위 entry point이고,asyncio.gather로 여러 awaitable을 동시에 실행할 수 있습니다.asyncio.create_task로 백그라운드 태스크를 만들어 다른 작업과 병렬로 돌릴 수도 있습니다.
짧은 예제
python
async def poll():
while True:
print("polling")
await asyncio.sleep(1)
asyncio.create_task(poll())
await fetch_data()빠른 정리
| 키워드 | 역할 |
|---|---|
async def | coroutine 정의 |
await | awaitable 결과 기다리기 |
asyncio.run | 루프 실행 |
gather | 여러 coroutine 병렬 |
주의할 점
동기 함수 안에서 await을 직접 쓸 수 없으므로, 필요하면 asyncio.run으로 감싼 coroutine을 호출하거나 loop.create_task를 쓰세요.