Differentiate between worker threads and clusters in Node JS. - GeeksforGeeks (2024)

Last Updated : 14 Nov, 2023

Summarize

Comments

Improve

In this article, we will learn about worker threads & clusters, along with discussing the significant distinction that differentiates between worker threads & clusters.

Table of Content

  • What is Worker Thread in Node.JS?
  • What is clusters in Node.JS?
  • Difference between Worker threads and Clusters
  • Conclusion

Let us first understand what is worker threads and clusters in Node.js?

What is Worker Thread in Node.JS?

Worker threads are the useful feature in Node.Js which allows us to run JavaScript code in parallel with the main thread. Before worker threads NodeJ.Js could execute one operation at a time. Worker threads provide the capability to perform parallel processing by creating separate threads.

Worker threads are useful for performing CPU-intensive JavaScript operations, but they don’t not help much with I/O intensive work. They are also able to share memory by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.

Creating a simple worker-thread

Example: Create two files named worker.js and index.js in your Node.Js project

Javascript

// worker.js

const { workerData, parentPort } = require('worker_threads')

console.log('Worker Threads by ' + workerData);

parentPort.postMessage({ fileName: workerData, status: 'Done' })

Javascript

// index.js

const { Worker } = require('worker_threads')

function runService(workerData) {

return new Promise((resolve, reject) => {

const worker = new Worker(

'./worker.js', { workerData });

worker.on('message', resolve);

worker.on('error', reject);

worker.on('exit', (code) => {

if (code !== 0)

reject(new Error(

`Worker Thread stopped with the exit code: ${code}`));

})

})

}

async function run() {

const result = await runService('GeeksForGeeks')

console.log(result);

}

run().catch(err => console.error(err))

Output: Here, the function runService() return a Promise and runs the worker thread. The function run() is used for calling the function runService() and giving the value for workerData.

Differentiate between worker threads and clusters in Node JS. - GeeksforGeeks (1)

Simple Worker Thread example

What is clusters in Node.JS?

Node.Js clusters are used to run multiple instances in single threaded Node application. By using cluster module you can distribute workloads among application threads. The cluster module allows us to create child processes that all share server ports. To handle heavy load, we need to launch a cluster of Node.js processes and hence make use of multiple cores.

Each child process has its own event loop, memory, V8 instance, and shares the same server port.

Creating a simple cluster

Example: Write the following code to create a cluster

Javascript

const cluster = require('cluster');

const os = require('os');

const express=require("express");

const app=express();

if (cluster.isMaster) {

// Master process code

console.log(`Master ${process.pid} is running`);

// Fork workers equal to the number of CPU cores

for (let i = 0; i < os.cpus().length; i++) {

cluster.fork();

}

// Listen for worker exit and fork a new one

cluster.on('exit', (worker, code, signal) => {

console.log(`Worker ${worker.process.pid} died`);

cluster.fork();

});

} else {

// Worker process code

console.log(`Worker ${process.pid} started`);

const port=8000;

app.listen(port,(req,res)=>{

console.log(`server running at port ${port}`);

});

}

Output:

Differentiate between worker threads and clusters in Node JS. - GeeksforGeeks (2)

Simple Cluster example

Explanation: Here, The master process (identified by cluster.isMaster) forks multiple worker processes.Each worker process (identified by cluster.isWorker) runs independently and performs its own tasks.The master process listens for worker exit events and forks a new worker when one exits.

Difference between Worker threads and Clusters:

Through both Worker threads and Clusters are mechanisms for concurrent and parallel processing, but still they have different use cases and operate at different levels of abstraction that differentiates both Worker threads and Clusters, which is given below.

Method

Worker Thread

Clusters

Granularity

Worker threads operate at thread level, providing a way to run JavaScript code in parallel within a single process.

Clusters operate at process level, allowing you to create multiple Node.js processes (workers) to handle incoming network requests.

Communication

Communication between worker threads is typically achieved through message passing using the postMessage API.

Communication between the master process and worker processes is achieved using IPC mechanisms.

Isolation

Worker threads have their own isolated JavaScript context, means they don’t share variables or memory directly.

Each worker process in a cluster is a separate Node.js process, which means they have their own memory space.

I/O Operations

Worker threads are not built for I/O-intensive operations, as Node.js’s built-in asynchronous I/O mechanisms are often more efficient.

Clusters are built for handle I/O-intensive operations efficiently. Each worker in a cluster can handle incoming requests independently.

Memory Sharing

Worker threads can share memory using ArrayBuffer or SharedArrayBuffer instances, which allows more direct communication and shared data.

Clusters operate in separate processes so memory is isolated between them. Communication between clusters is often achieved through message passing.

Use Case

Worker threads are good for CPU-intensive tasks where parallel processing can significantly improve performance.

Clusters are good for improving the scalability of networked applications by distributing incoming requests among multiple processes.

Conclusion:

The decision on whether to use worker threads, which used for parallelizing CPU-intensive tasks within single process, or Clusters, which are used to distribute operations across multiple processes utilizing the multi processor, for better scalability and dependability, depends on the particular usecase of the application.



S

souravsharma098

Differentiate between worker threads and clusters in Node JS. - GeeksforGeeks (3)

Improve

Next Article

Difference between Web Role and Worker Role in Node.js

Please Login to comment...

Differentiate between worker threads and clusters in Node JS. - GeeksforGeeks (2024)
Top Articles
5 Proven Tips to Protect Your Money During a Crypto Crash
How To Travel The Best Of Seychelles On A Budget
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6023

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.