|
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 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-threadExample: Create two files named worker.js and index.js in your Node.Js project Javascript
Javascript
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. 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 clusterExample: Write the following code to create a cluster Javascript
Output: 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.
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. |
Reffered: https://www.geeksforgeeks.org
Node.js |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |