I know maybe it's a stupid question. I'm not good at OS knowledge.
Usually the number of cluster/process we fork is the CPU cores count, like the Nodejs offical Doc display.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
But I'm confused what if we fork the cluster more than the number of CPU cores, what it gonna happen?
Is it the empirical value, best practice or any other reason?
Node. js absolutely does scale on multi-core machines. Yes, Node. js is one-thread-per-process.
Not many realize that NodeJS runs in a single thread by default. Besides, it utilizes only one CPU core for this thread. So, for example, if you're using a 4 core machine, Node will only be using a single core.
Node. js applications can be parallelized using cluster modules in order to use the system more efficiently. Running multiple processes at the same time can be done using few lines of code and this makes the migration relatively easy, as Node.
Since Node. js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node. js provides support for deployment on multiple-core systems, to take greater advantage of the hardware.
But I'm confused what if we fork the cluster more than the number of CPU cores, what it gonna happen?
Nothing will happen, everything will still work, but putting more than one CPU-intensive thread or process per core will not make the application any faster - if anything, it may only make is slower because the core will waste some portion of the time on the context switches between the threads.
If you have CPU-bound operations then the optimal number of threads/processes per core is always 1. For I/O-bound operations it shouldn't really matter as most of the time the processes will not do any computations anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With