python에서 비동기를 구현하기 위해서는 많은 것이 필요하다. 우선 동기와 비동기는 무엇인가? 느낌적인 이해는 쉽지만 말로 설명하라고 했을때 명쾌한 답이 나오기 어려운 개념이라고 생각된다.



파이썬에서는 async와 await를 활용한 네이티브 코루틴(Native Coroutine)과 yield를 활용한 제너레이터 기반 코루틴(Generator-based Coroutine) 두가지 코루틴이 있으며 네이티브 코루틴(Native Coroutine)를 다룰 것이다.
글쓴이는 회사에서 asyncio, AIOHTTP를 활용한 I-O bound 작업을 줄이기 위해 비동기 함수를 사용하였고 상대 서버 상황에 따라서 비동기에 대한 제약도 많이 생길 수 있다는 것을 느꼈고 cs 개념적으로도 중요한 공부였다고 생각한다.
# 일반적인 routine subroutine
def add(a, b):
return a + b
def main():
a = 1
b = 2
c = add(a, b)
main()
-----------------------------------
# 비동기 함수
async def sleeping(sec):
print(f'{sec} 진입시간 : {datetime.datetime.now()}')
await asyncio.sleep(sec)
print(f'{sec} 종료시간 : {datetime.datetime.now()}')
return sec
async def main():
task = [asyncio.create_task(sleeping(sec)) for sec in range(1, 4)]
task_result = await asyncio.gather(*task)
return task_result
result = asyncio.run(main())
참조
https://webclub.tistory.com/605
https://docs.python.org/ko/3/library/asyncio-task.html