码迷,mamicode.com
首页 > Windows程序 > 详细

Node项目通过cluster API充分利用多核CPU

时间:2014-12-26 16:56:10      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:

默认的一个Node项目只有一个Master进程,通过cluster API来管理此进程,可以为每核增加一个worker,就叫分支进程吧

技术分享

示例

var cluster = require(‘cluster‘);
var http = require(‘http‘);
//获取服务器的CPU核数
var numCPUs = require(‘os‘).cpus().length;
if (cluster.isMaster) {
    for (var i = 0; i < numCPUs; i++) {
        //为CPU的每核创建一个分支进程
        cluster.fork();
    }
    cluster.on(‘death‘, function(worker) {
        console.log(‘Worker ‘ + worker.pid + ‘ died.‘);
    });
} else {
    http.Server(function(req, res) {
        res.writeHead(200);
        res.end(‘I am worker ID ‘ + process.env.NODE_CLUSTER_ID);
    }).listen(8000);
}

由于主进程与分支进程分别在不同的操作系统进程中,它们不能共享全局变量,cluster API提供了主进程与分支进程之间通信的方法

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) {
			workers[i].on(‘message‘, function(message) {
				if (message.cmd == ‘incrementRequestTotal‘) {
					requests++;
					for (var j = 0; j < numCPUs; 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(200);
		res.end(‘Worker ID ‘ + process.env.NODE_WORKER_ID
			+ ‘ says cluster has responded to ‘ + requests
			+ ‘ requests.‘);
		process.send({cmd: ‘incrementRequestTotal‘});
	}).listen(8000);
}






Node项目通过cluster API充分利用多核CPU

标签:

原文地址:http://my.oschina.net/lhplj/blog/360902

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!