Abdelfattah
Abdelfattah

Reputation: 725

What is the difference between Child_process and Worker Threads?

I am trying to understand Threading in NodeJS and how it works.

Currently what i understand:

Cluster: -

Child_process:

Worker threads:

1) Why worker threads is better than child process and when we should use each of them?

2) What would happen if we have 4 cores and clustered/forked nodeJS webserver 4 times(1 process for each core), then we used worker threads (There is no available cores) ?

Upvotes: 63

Views: 27088

Answers (1)

Sudhir Dhumal
Sudhir Dhumal

Reputation: 970

You mentioned point under worker-threads that they are same in nature to child-process. But in reality they are not.

Process has its own memory space on other hand, threads use the shared memory space.

Thread is part of process. Process can start multiple threads. Which means that multiple threads started under process share the memory space allocated for that process.

I guess above point answers your 1st question why thread model is preferred over the process.

2nd point: Lets say processor can handle load of 4 threads at a time. But we have 16 threads. Then all of them will start sharing the CPU time.

Considering 4 core CPU, 4 processes with limited threads can utilize it in better way but when thread count is high, then all threads will start sharing the CPU time. (When I say all threads will start sharing CPU time I'm not considering the priority and niceness of the process, and not even considering the other processes running on the same machine.)

My Quick search about time-slicing and CPU load sharing:

  1. https://en.wikipedia.org/wiki/Time-sharing
  2. https://www.tutorialspoint.com/operating_system/os_process_scheduling_qa2.htm

This article even answers how switching between processes can slow down the overall performance.

Worker threads are are similar in nature to threads in any other programming language.

You can have a look at this thread to understand in overall about difference between thread and process: What is the difference between a process and a thread?

Upvotes: 35

Related Questions