A single Node instance runs in a single thread. to make full use of the multi-core system, we can run the Node process cluster to handle the load.
That is to say, if the system has 8 cores, a single Node instance can only use one of them. The workers concept of the cluster package can be used to make full use of all the cores. Interestingly, they can share the same port.
This module is still in the experimental stage.
[Javascript]
Var cluster = require ('cluster ');
Var http = require ('http ');
Var numCPUs = require ('OS'). cpus (). length;
If (cluster. isMaster ){
// Fork workers.
Require ('OS'). cpus (). forEach (function (){
Cluster. fork ();
});
// In case the worker dies!
Cluster. on ('eg', function (worker, code, signal ){
Console. log ('worker' + worker. process. pid + 'died ');
});
// As workers come up.
Cluster. on ('listenering', function (worker, address ){
Console. log ("A worker with #" + worker. id + "is now connected to" + \
Address. address + \
":" + Address. port );
});
// When the master gets a msg from the worker increment the request count.
Var reqCount = 0;
Object. keys (cluster. workers). forEach (function (id ){
Cluster. workers [id]. on ('message', function (msg ){
If (msg.info & msg.info = 'reqservmaster '){
ReqCount + = 1;
}
});
});
// Track the number of request served.
SetInterval (function (){
Console. log ("Number of request served =", reqCount );
},1000 );
} Else {
// Workers can share the same port!
Require ('http'). Server (function (req, res ){
Res. writeHead (200 );
Res. end ("Hello from Cluster! ");
// Configure y the master about the request.
Process. send ({info: 'reqservmaster '});
}). Listen (8000 );
}
On a 4-core computer, the output is as follows:
[Javascript]
Number of request served = 0
A worker with #2 is now connected to 0.0.0.0: 8000
A worker with #4 is now connected to 0.0.0.0: 8000
A worker with #1 is now connected to 0.0.0.0: 8000
A worker with #3 is now connected to 0.0.0.0: 8000
Number of request served = 0
...
Number of request served = 2
..
Number of request served = 4
...
Number of request served = 6