Hyesung Oh

Python, Node.js로 끄적여본 async, await 본문

DEV/Python

Python, Node.js로 끄적여본 async, await

혜성 Hyesung 2022. 8. 11. 05:00
반응형

Python에서 async, await로 비동기 프로그래밍을 작성하다, 간혹 Node.js 쪽 코드 작성을 하다보면 매우 유사한점을 느껴 내부 작동방식도 유사한지 공부해보았다. 자세한 내용은 다루지 않겠지만 그래도 내가 이해한 내용의 핵심만 요약해보았다.

Python은 generator를 이용해 corutine을 구현하여 비동기 시스템을 구현하였다. 그리고 코루틴 테스크간의 제어권 컨트롤의 중심에 event loop process가 있다. python의 stack이 heap 영역에 존재하는 언어 특성을 살린 케이스이다.

Node.js는 event loop 역할은 유사하나, 좀 더 event driven 적인 접근이다. event들은 callback 함수가 return한 결과이고 이들을 관리하는 별도 stack이 존재한다. 

import asyncio


def shout(ft: asyncio.Future):
    print("im done")


async def wait_and_print():
    future = asyncio.create_task(asyncio.sleep(10))
    future.add_done_callback(shout)
    print(3)
    await future

if __name__ == "__main__":
    # regard asyncio.run which is event loop as node.js runtime
    asyncio.run(wait_and_print())

위 python 코드는 아래 node.js 코드와 동일하게 동작한다. 물론 내부적으로는 같지 않지만 겉으로 보기엔 같은 코드이다.

function waiteAndPrint() {
  setTimeout(() => {
    console.log("im done")
  }, 10);
  console.log(3)
}

waiteAndPrint()

Python

await가 호출되면 동기적으로 호출된다.
main coroutin에서 await가 호출되면 제어권이 event loop에게 간다. 이 부분이 제일 중요하다
async가 붙은 함수는 coroutin 함수이며 await없이 호출 시에 coroutin 객체가 return 될 뿐 event loop에 등록되지 않는다.
asyncio.create_task를 호출하면 event loop에 등록된다. await한 coroutin이 완료되면 event가 발생하며 다시 제어권이 await 다음코드로 넘어가게 된다. 

- https://itnext.io/async-await-what-happens-under-the-hood-eef1de0dd881

 

Async/Await — What Happens Under The Hood

Understand how async/await works in a more detailed way and what Tasks, Threads, and ThreadPool has to do with them

itnext.io

- https://medium.com/@a.j.kaijanaho/python-async-await-from-the-ground-up-980296be1c99

 

Python async/await From the Ground Up

How to Use Python Coroutines Like You Mean It

medium.com

 

Node.js

await가 호출되면 동기적으로 실행된다.
async가 붙은 함수를 그냥 호출 할 수 있다. 다만 Promise를 꼭 return해야만 한다. python에서는 asyncio.create_task 없이 호출하면 실행되지 않는 것과 큰 차이점이다.
await를 하는 부분에 있어서 그 다음 코드들은 동기적으로 실행된다. 이는 promise.then처럼 Callback으로 아래 코드들을 실행하는 것과 같지만 가독성을 올려주며 비동기적 사고를 하지 않아도 되게 해준다. 또한 await를 호출하면 node.js의 event loop로 해당 I/O event는 넘어가게 되고 call stack은 비게 되어 다음 요청을 받을 수 있게 된다.

- https://dev.to/_staticvoid/node-js-under-the-hood-3-deep-dive-into-the-event-loop-135d

 

Node.js Under The Hood #3 - Deep Dive Into the Event Loop

In our last article we talked about call stacks, stack frames, stack overflow and a bunch of other JS...

dev.to

- https://medium.com/@mmoshikoo/event-loop-in-nodejs-visualized-235867255e81

 

Event Loop in NodeJs — Visualized

Event Loop is explained with excellent visualizations, the article also explains the deeper parts such as Micro & Macro Tasks and more.

medium.com

반응형
Comments