Nodejs is multi threading or multi processing?
Created at 2019-09-24 Updated at 2024-11-07 - 3 min. read
Even before we start a discussion about the topic, “Node works on multithreading or multi processing?”.
Let understand basic terminology that would be beneficial to understand the overall concept.
Process
It means any program is in execution. Process control block contains the information about processes for example: Process priority, process id, process state, CPU, register etc. A process can create other processes which are known as Child Processes. Process takes more time to terminate and it is isolated means it does not share memory with any other process.Thread
It is a program execution that uses process resources for accomplishing the task. All threads within a single program are logically contained within a process.A thread have 3 states: running, ready, and blocked.Thread takes less time to terminate as compared to process.
Node run on a single thread. So how does it able to scale in cluster? It’s basically due to module called child process. The child_process module enables us to access Operating System functionalities by running any system command inside a, well, child process.
We can control that child process input stream, and listen to its output stream. We can also control the arguments to be passed to the underlying OS command, and we can do whatever we want with that command’s output. We can, for example, pipe the output of one command as the input to another (just like we do in Linux) as all inputs and outputs of these commands can be presented to us using Node.js streams.
So child process is able to create process using 4 different functions. Each function has its own pros and cons.
- exec
- execFile
- spawn
- fork
exec
This method will spawn a subshell and execute the command in that shell and buffer generated data. When the child process completes, callback function is called.
execFile
It is similar to exec() except that it does not spawn a shell by default. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than exec().
spawn
This method spawns an external application in a new process and returns a streaming interface for I/O.
fork
This method is a special case of spawn() used specifically to spawn new Node.js processes. Like spawn(), a ChildProcess object is returned. The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child
Hence nodejs uses multiple process to create cluster for scalling. As it is based on JS which is single threaded. So it never uses multiple threads distribute its work. Instead it divides the work to different process which are run on different processor of OS.