1. 程式人生 > >多核cluster 發揮nodejs多核優勢

多核cluster 發揮nodejs多核優勢

var cluster=rquire('cluster');

var http=require('http');

var numCPU=require('OS'cpus().length;//獲得cpu 數量

if(cluster.isMaster){

require('OS').cpus().forEach(function(){

cluster.fork();

});

cluster.on('exit',function(worker,code,single){

console.log('work'+worker.process.pid+'died');

});

cluster.on('listening',functon(worker,address){

console.log('A work with'+ worker.id+'is now connected to'+address.address+","+address.port)

});

}

else{

var server=http.createserver(app);

server.listen(...);

console.log(...);

}

程序通訊

if(cluseter.isMaster){

var worker_process=cluster.fork();

worker.process.on('message',function(msg){

if(msg.cmd==''){

}

}

else{

process.send({cmd:'notifRequest'});

}