0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00

cluster: add example for message passing

This commit is contained in:
Ryan Dahl 2011-11-04 15:33:49 -07:00
parent 5496e67f83
commit 1e3e6b7c15

View File

@ -34,6 +34,44 @@ Running node will now share port 8000 between the workers:
Worker 2438 online
Worker 2437 online
The difference between `cluster.fork()` and `child_process.fork()` is simply
that cluster allows TCP servers to be shared between workers. `cluster.fork`
is implemented on top of `child_process.fork`. The message passing API that
is available with `child_process.fork` is available with `cluster` as well.
As an example, here is a cluster which keeps count of the number of requests
in the master process via message passing:
var cluster = require('cluster');
var http = require('http');
var numReqs = 0;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < 2; i++) {
var worker = cluster.fork();
worker.on('message', function(msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs++;
}
});
}
setInterval(function() {
console.log("numReqs =", numReqs);
}, 1000);
} else {
// Worker processes have a http server.
http.Server(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
// Send message to master process
process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}
### cluster.fork()
Spawn a new worker process. This can only be called from the master process.