This question is more related to computer science, but it’s asked quite often in Node.js interviews, so it makes sense to cover it in this category. First, let’s define a process and a thread.
Process is a separately running program for which the operating system allocates resources. The key idea behind a process is isolation, so issues in one process don’t directly affect others, and communication happens via IPC (inter-process communication), for example through pipes, sockets, and so on.
Thread is a sequence of instructions executed within a process and has its own execution context (Thread Execution Context). Since threads exist within a process, they share memory, which makes them a great solution for parallel tasks. Also, because there’s no need for IPC, threads run much faster than processes.
Below is a diagram of a typical Node.js API that uses multiple processes. It clearly shows that threads are inside processes, and the process itself is an isolated container. Also, note the Libuv icons - they appear both in the process and in the worker threads. This means that when you create a thread/process, a separate Event Loop will be created.
Let’s summarize the key differences:
- A process is a top-level container.
- Each process has its own memory, while threads share memory.
- A process has an independent lifecycle, while a thread depends on the process.
- Communication between processes is slower and less efficient than communication between threads.