DEV Community

loading...
Cover image for Is Node multithreaded?

Is Node multithreaded?

Int_Shibin
Software engineer , UI enthusiast
・2 min read

As we all know that javascript is a scripting language used for building web application. Node introduced to leverage the capacity of javascript to make it as a scalable network language.

As per official definition Node is an asynchronous event-driven JavaScript runtime. this is in contrast to thread based networking.

First let us make a basic understanding of thread and process's. The basic instance of a computer program is called a process. within a single process we can have multiple things called threads , threads are kind of set of instructions that computer CPU needs to do and Scheduling is the ability of OS to decide which thread to process at anyinstance in time. Urgent threads should not be waited for too long.

strategies use to increase the rate in which these threads are getting processed are

  • Add more CPU cores to the machine.
  • More closely examine the work that being done by each thread.

Now let us understand the design of node ecosystem
Alt Text

Node js ecosystem consists of three entities node js interface, v8 library and libUV library. Here 70 % of v8 and 100% of libUV is written in c++. Node leveraging functions from both these libraries. libUV is an open source c++ project gives node access to underlying O.S , file system and networking.
Process.binding() connect js and c++ functions . V8 connects values between js and c++ worlds.

Now we can come back to our thread discusisons. So node uses a hybrid implimentation of threading system . Node event model is based on an event loop. Whenever we start a node function it will run inside a event loop , which is truly single threaded. Node js simply enters the event loop, after executing the input script. nodejs exits the event loop when there is no more callbacks to perform.

For some expesive functions Node LibUV(c++) part decide to execute outside the single thread which is used for eventloop execution. For this execution we have a threadpool which is a series of four(by default and can be increase) threads that are used to execute computational intensified tasks

Alt Text

How thread pool fitting in node ecosystem ? , tasks running in the threadpool are consdered as the pending operation , which is considered as one of the three kinds of events which happens in the event loop other 2 are

  • pending timeout operations.
  • pending OS tasks.

So in this way we can conclude that Node is truly single threaded but few heavy function executions are taking place in the multi threaded thread pool.

References:
Node official document.
Udemy Nodejs: advanced concepts.

Discussion (0)