两个文件
第一个文件,文件名称 master.js,代码为:
var fork = require("child_process").fork;
var cpus = require("os").cpus();//获取cpu核数
for (var i = 0; i < cpus.length; i++) {
fork('./worker.js');
}
第二个文件为worker.js,代码为:
var http = require("http");
var port = Math.round((1 + Math.random()) * 1000); //随机端口,防止占用无法启动
console.log(port);
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('hello word \n' + port);
}).listen(port, '127.0.0.1' );
总结:通过child_process.fork()函数可以实现进程的复制,一次实现多cpu的利用