在双核上开两个worker,阻塞一个worker后,其他worker也被阻塞了。开10个worker也一样,是我cpu核心太少吗?还是本来就这样。
连续发送两个请求,只有一个核是100%,并且从输出看只有一个节点在工作:
A worker with #1 is now connected to 0.0.0.0:8000
A worker with #2 is now connected to 0.0.0.0:8000
Worker #1 has a request
Worker #1 make a response
Time: 5000ms
Worker #1 has a request
Worker #1 make a response
Time: 5001ms
脚本文件: var cluster = require(‘cluster’); var http = require(‘http’); var numCPUs = require(‘os’).cpus().length;
if (cluster.isMaster) {
require('os').cpus().forEach(function(){
cluster.fork();
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
cluster.on('listening', function(worker, address) {
console.log("A worker with #"+worker.id+" is now connected to " +
address.address +
":" + address.port);
});
} else {
http.createServer(function(req, res) {
console.log('Worker #' + cluster.worker.id + ' has a request');
res.writeHead(200);
console.time('Time');
function sleep(milliSeconds) {
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
sleep(5000);
res.end("hello world\n");
console.log('Worker #' + cluster.worker.id + ' make a response');
console.timeEnd('Time');
}).listen(8000);
}
8 回复
我的四核,两个核用到了。
C:\dev\test\node-module\cluster>node test.js
cpu#:4
cpu#:4
A worker with #1 is now connected to 0.0.0.0:8000
cpu#:4
A worker with #4 is now connected to 0.0.0.0:8000
cpu#:4
A worker with #3 is now connected to 0.0.0.0:8000
cpu#:4
A worker with #2 is now connected to 0.0.0.0:8000
Worker #2 has a request
Worker #2 make a response
Time: 5001ms
Worker #2 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #3 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #3 make a response
Time: 5001ms
Worker #3 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #3 make a response
Time: 5000ms
Worker #3 has a request
Worker #2 make a response
Time: 5000ms