Duplexing - Concurrency in Node JS
Duplexing - Concurrency in Node JS
Imagine the event loop as the brain of Node.js. It's a continuous loop that
manages events and tasks. Here's how it works:
● Efficiency: The event loop doesn't get blocked waiting for I/O
operations, allowing your application to handle more concurrent
tasks.
● Responsiveness: Your application remains responsive while I/O
operations are happening in the background.
2. Libuv and Thread Pool (Behind the Scenes):
● Event Loop: Similar to the main event loop, libuv's event loop
manages its own set of events and tasks related to I/O operations.
● Thread Pool: For certain I/O operations that require more processing
power, libuv can utilize a thread pool. This pool consists of multiple
threads that can run concurrently to perform these tasks.
● The main event loop manages your JavaScript code and I/O
operations that don't require heavy processing.
● Libuv's event loop and thread pool handle more demanding I/O tasks
efficiently, freeing up the main thread for your JavaScript code.
The cluster module is another tool for concurrency in Node.js. It allows you
to create multiple worker processes that share the same server port.
Here are some code examples that illustrate the concepts discussed:
const fs = require("fs");
console.log("Starting operation...");
In this example:
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
In this example:
● The main thread creates a worker and sends data to it (the number to
calculate the Fibonacci sequence).
● The worker calculates the Fibonacci number (CPU-bound task) in a
separate thread.
● The worker sends the result back to the main thread using message
passing.
if (cluster.isMaster) {
const numCPUs = require('os').cpus().length;
console.log(`Master process ${process.pid} is
running`);
Explanation: