| Node.js is inherently single-threaded, meaning it runs on a single thread by default. However, you can create a multi-threaded server using the worker_threads module, which allows you to run JavaScript code in parallel threads, or by using the cluster module to take advantage of multiple CPU cores. Here's an example using the cluster module to create a multi-threaded server: Multi-Threaded HTTP Server with cluster const cluster = require('cluster');
const http = require('http');
const os = require('os');
// Get the number of CPU cores
const numCPUs = os.cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers (one per CPU core)
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// Listen for dying workers and replace them
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
// Workers can share any TCP connection, in this case, an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello, World!\n');
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}
How it works: cluster.isMaster: The code checks if the current process is the master process. If it is, the master process will fork worker processes.cluster.fork(): This method is used to create a new worker process. The number of workers is typically set to the number of CPU cores available, so each core can handle a separate process.- Worker processes: Each worker runs a copy of the server code. They all share the same server port and can handle requests concurrently.
cluster.on('exit', ...): This event listener ensures that if a worker dies, the master process will start a new worker to replace it.
Running the multi-threaded server: - Save the code to a file, e.g.,
clustered-server.js. Run the server using Node.js: node clustered-server.js
- The server will listen on port
3000, and you will see multiple worker processes han |