Node.js Event loop

前端 未结 5 1647
借酒劲吻你
借酒劲吻你 2020-11-30 20:10

Is the Node.js I/O event loop single- or multithreaded?

If I have several I/O processes, node puts them in an external event loop. Are they processed in a sequence

5条回答
  •  既然无缘
    2020-11-30 21:10

    From Willem's answer:

    The Node.js event loop runs under a single thread. Every I/O call requires you to register a callback. Every I/O call also returns immediately, this allows you to do multiple IO operations in parallel without using threads.

    I would like to start explaining with this above quote, which is one of the common misunderstandings of node js framework that I am seeing everywhere.

    Node.js does not magically handle all those asynchronous calls with just one thread and still keep that thread unblocked. It internally uses google's V8 engine and a library called libuv(written in c++) that enables it to delegate some potential asynchronous work to other worker threads (kind of like a pool of threads waiting there for any work to be delegated from the master node thread). Then later when those threads finish their execution they call their callbacks and that is how the event loop is aware of the fact that the execution of a worker thread is completed.

    The main point and advantage of nodejs is that you will never need to care about those internal threads and they will stay away from your code!. All the nasty sync stuff that should normally happen in multi threaded environments will be abstracted out by nodejs framework and you can happily work on your single thread (main node thread) in a more programmer friendly environment (while benefiting from all the performance enhancements of multiple threads).

    Below is a good post if anyone is interested: When is the thread pool used?

提交回复
热议问题