VOOZH about

URL: https://www.geeksforgeeks.org/node-js/how-to-handle-child-threads-in-node-js/

⇱ How to handle Child Threads in Node.js ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to handle Child Threads in Node.js ?

Last Updated : 10 Sep, 2021

Node.js is a single-threaded language and uses the multiple threads in the background for certain tasks as I/O calls but it does not expose child threads to the developer.
But node.js gives us ways to work around if we really need to do some work parallelly to our main single thread process.
Child Process in Node: The child_process module gives the node the ability to run the child process by accessing operating system commands.
Example: Filename: parallelProcess.js 
 

Filename: main.js 
 

Output: 
 

Before process
After process
Child Process Starts
Data processed
Child process terminated and returned


Worker Threads The worker_threads module enables the use of threads that execute JavaScript in parallel. Worker's threads are useful for performing CPU-intensive JavaScript operations. They will not help much with I/O-intensive work which can be done better using Node.js built-in asynchronous I/O operations.
Example: 
 

Output: 
 

Thread send message: Hello World!
Worker exit


The process has its own memory space on other hand, threads use the shared memory space. Thread is part of the process. Since worker_threads make new threads inside the same process it requires fewer resources.
Reference: 
https://nodejs.org/api/child_process.html 
https://nodejs.org/api/worker_threads.html
 

Comment
Article Tags:

Explore