The default node project has only one master process, which is managed by the cluster API, and a worker is added to each core, called the branching process.
Example
var cluster = require (' cluster '); var http = require (' http ');//Gets the number of CPU cores of the server var Numcpus = require (' OS '). CPUs (). Length;if ( Cluster.ismaster) { for (var i = 0; i < Numcpus; i++) { //Create a branch process for each core of the CPU cluster.fork (); } Cluster.on (' Death ', function (worker) { console.log (' worker ' + Worker.pid + ' died. '); });} else { http. Server (function (req, res) { res.writehead (); Res.end (' I am worker ID ' + Process.env.NODE_CLUSTER_ID); }). Listen (8000);}
The Cluster API provides a way to communicate between the main and branch processes because the master and spoke processes are separate from each other in the operating system process, and they cannot share global variables.
var cluster = require (' cluster '); var http = require (' http '); var Numcpus = require (' OS '). CPUs (). Length;var workers = {};var Requests = 0;if (Cluster.ismaster) {for (var i = 0; i < Numcpus; i++) {Workers[i] = cluster.fork ();(function (i) {work Ers[i].on (' message ', function (message) {if (Message.cmd = = ' Incrementrequesttotal ') {requests++;for (var j = 0; J < num CPUs; J + +) {workers[j].send ({cmd: ' updateofrequesttotal ', requests:requests});}) (i);} Cluster.on (' Death ', function (worker) { console.log (' worker ' + Worker.pid + ' died. ');} );} else {Process.on (' Message ', function (message) {if (Message.cmd = = ' Updateofrequesttotal ') {requests = message.requests;}}); http. Server (function (req, res) {Res.writehead ($); Res.end (' Worker ID ' + process.env.node_worker_id+ ' says cluster has RESPO nded to ' + requests+ ' requests. '); Process.send ({cmd: ' incrementrequesttotal '}). Listen (8000);}
Node project leverages multi-core CPUs with Cluster API