asyncio는 coroutine을 사용하여 Python에서 비동기 처리를 구현할 수 있게 해주는 라이브러리입니다.
async-await 구문 (Coroutine)
비동기 함수를 선언하고 그 안에서 비동기 작업을 기다립니다. await과 함께 나오는 작업이 다 완료되기 전 까지는 다음 줄이 실행되지 않습니다. 여기서 async def로 정의된 함수를 coroutine이라고 합니다.
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay) # delay만큼 시간이 흐르기 전까지는 더 진행되지 않습니다.
return what
run()
async 함수를 실행하려면 asyncio.run()을 사용하면 됩니다. 일반적으로 진입점에서 한 번만 호출하는 것이 원칙입니다.
async def main():
result = await say_after(3, "finished") # say_after()가 끝날 때 까지 대기
print(result)
asyncio.run(main()) # 비동기 함수 실행
togather()
여러 개의 coroutine을 동시에 실행하고 모든 결과를 모아서 받고 싶을 때 사용합니다.
async def main():
results = await asyncio.togather(
say_after(1, "hello"),
say_after(2, "how are you")
)
print(results)
asyncio.run(main())
create_task()
지금의 coroutine은 await와 함께 호출해야 하므로 해당 coroutine의 작업이 완료되기 전 까지 대기해야 합니다. 만약 대기하지 않고 이후의 코드를 먼저 실행시키고자 한다면, asyncio.create_task()를 사용해야 합니다.
async def main():
await say_after(3, "a")
print("b")
print("c")
# 출력 순서는 a -> b -> c
async def main():
task = asyncio.create_task(say_after(3, "a")) # event loop queue에 작업을 추가
print("b")
print("c")
await asyncio.sleep(4) # 대기하는 동안 queue에 있던 작업을 수행
# 출력 순서는 b -> c-> a
※ JavaScript는 기본적으로 Nonblocking이기 때문에 비동기 함수가 나중에 실행되어 b, c, a 순서로 처리됩니다. Python은 기본적으로 Blocking이어서 비동기 함수가 앞에 와도 무조건 대기하여 a, b, c 순서로 처리됩니다.
asyncio를 사용하면 coroutine이 await를 만나 대기할 때 다른 함수에게로 제어권을 넘겨줄 수 있습니다. 이 성질을 이용해 multithreading과 비슷하게 단일 thread만으로도 동시성(concurrency)을 제어할 수 있습니다.
728x90
'Language > Python' 카테고리의 다른 글
| [Python] Syntax | 03. Decorator(@) (0) | 2026.02.16 |
|---|---|
| [Python] Event Loop (0) | 2026.02.16 |
| [Python] Closure (0) | 2026.02.15 |
| [Python] Garbage Collection (0) | 2026.02.15 |
| [Python] 동시성과 GIL(Global Interpreter Lock) (0) | 2026.02.15 |