How the single threaded non blocking IO model works in Node.js

后端 未结 7 981
抹茶落季
抹茶落季 2020-11-22 05:29

I\'m not a Node programmer, but I\'m interested in how the single threaded non blocking IO model works. After I read the article understanding-the-node-js-e

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 06:03

    Node.js is based on the event loop programming model. The event loop runs in single thread and repeatedly waits for events and then runs any event handlers subscribed to those events. Events can be for example

    • timer wait is complete
    • next chunk of data is ready to be written to this file
    • theres a fresh new HTTP request coming our way

    All of this runs in single thread and no JavaScript code is ever executed in parallel. As long as these event handlers are small and wait for yet more events themselves everything works out nicely. This allows multiple request to be handled concurrently by a single Node.js process.

    (There's a little bit magic under the hood as where the events originate. Some of it involve low level worker threads running in parallel.)

    In this SQL case, there's a lot of things (events) happening between making the database query and getting its results in the callback. During that time the event loop keeps pumping life into the application and advancing other requests one tiny event at a time. Therefore multiple requests are being served concurrently.

    event loop high level view

    According to: "Event loop from 10,000ft - core concept behind Node.js".

提交回复
热议问题