논블로킹 IO 동작원리

GonnabeAlright·2022년 1월 30일
0
post-thumbnail

Node.js is a JavaScript runtime environment that runs on the Chrome V8 engine and is used for server-side scripting. It takes requests from users, processes those requests, and returns responses to the corresponding users.

Some important Node.js features are:

- It is based on single-threaded architecture: Since node.js gets multiple requests from multiple users it executes one command at a time. Due to this it can handle concurrent client requests very effectively and has good performance.
- It uses an event-driven non-blocking-based IO model: Whenever the node server is started, it initiates certain variables and functions and then waits for events to occur, whenever an event is detected a callback function is assigned to that particular event. Event-driven architecture makes the server highly scalable and it does not wait for an API to return data, it moves to the next API immediately for the next request. Non-blocking operation means the server will not block itself for one request. Non-blocking call only initiates the operation and the response is provided later, meanwhile, it can continue with other client requests.

Example:

If we get requests from two users A and B. With non-blocking IO we can initiate the request for A and then immediately for B without waiting for the response to the request of A. Hence we can say with the help of non-blocking IO we can eliminate the use of multi-threading since the node server can handle multiple requests simultaneously.

Working of single-threaded non-blocking IO:

  • When the client sends a request to the server, this request is called an event. These all requests get stored in an event queue. The single thread present in the event loop assigns this request to one of the threads present in the internal thread pool.
  • This thread reads the client request, processes the request, performs any blocking IO operations if needed, and prepares the final response to be sent back to the server. The event loop sends this response back to the respective client.
  • The event loop infinitely receives requests and processes them.
  • There is no need for multiple threads because of Event Loop. Because of this event loop and concept of single threading, node.js uses lesser resouces and memory.

이벤트 루프 동작을 시각적으로 보여주는 사이트:
http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D

0개의 댓글