Asyncio 사용 해보기(1)

code_able·2022년 11월 25일
0

async/await 구문을 사용하여 동시성 코드를 작성하는 라이브러리 입니다.
async def로 코루틴 함수를 작성하며 return은 await 구문으로 받습니다.

이러한 방식을 비동기 프로그래밍이라고 하며
서버의 성능을 최대한 끌어 올려 줄 수 있는 개발 방법 입니다.

  • Coroutine : 코루틴은 응답이 지연되는 부분에서 이벤트 루프에 통제권을 줄 수 있으며, 응답이 완료되었을 때 멈추었던 부분부터 기존의 상태를 유지한 채 남은 작업을 완료할 수 있는 함수를 의미합니다. 파이썬에서 코루틴이 아닌 일반적인 함수는 서브루틴(Subroutine)이라고 합니다.

async def run_process():
    return "hello"
    
 async def main():
    process = run_process()
    result = await process
  • Task : 코루틴을 간단한 래퍼로 감싼 객체

async def run_process():
    return "hello"
    
async def main():
  t = asyncio.create_task(run_process())
  co = doSomethingAnother()
  print(await co)
  await t
  • Future: 함수를 처리하는 시점에서 결과 값이 리턴 될 것이라는 약속으로 결과를 처리한 후 결과가 지연 없이 리턴 될 수 있도록 해준다.
futures = [asyncio.ensure_future(main(param)) for param in params]
await asyncio.gather(*futures)
profile
할수 있다! code able

0개의 댓글