虽说nodejs是单线程的,但是它还是容许多线程操作,它把当前线程作为主线程,可分割出一些从线程,
虽说是分割的,但是字线程和主线程具有同样的功能,可同样监听同一个端口,当主线程阻塞时,从线程可以代替他工作,从线程和主线程可以通信
说明:例子实在学习过程中从原文中得来的。
var cluster = require("cluster");//通过cluster可以分出一些字线程
var http = require("http");
var numCPUs = require("os").cpus().length;
console.log(numCPUs);
var rssWarn = (12 * 1024 * 1024);
var heapWarn = (10 * 1024 * 1024);
if (cluster.isMaster) {
for (i = 0; i < numCPUs; i++) {
var worker = cluster.fork();
worker.on("message", function (m) {
if (m.memory) {
if (m.memory.rss > rssWarn) {
console.log(\'Worker\' + m.process + " using to much memory");
}
else {
console.log(\'Worker\' + m.process + " is processing");
}
}
})
}
cluster.on("death", function (worker) {
console.log("worker " + worker.pid + \' died\');
cluster.fork();
});
}
else {
http.Server(function (req, res) {
res.writeHead(200);
res.end("Hello World\n");
}).listen(3000);
setInterval(function report() {
process.send({ "memory": process.memoryUsage(), "process": process.pid });
}, 1000);
}