How many child_processes should I fork() in node.js?

前端 未结 2 2120
终归单人心
终归单人心 2021-02-08 10:01

My question is quite simple. though, it may require different variable to be answered (i guess)

I\'m playing around with node.js and I\'m thinking of how to use it in a

2条回答
  •  Happy的楠姐
    2021-02-08 10:44

    The Node.js official documentation has an example of how to use cluster:

    var cluster = require('cluster');
    var http = require('http');
    var numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
      // Fork workers.
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
      cluster.on('death', function(worker) {
        console.log('worker ' + worker.pid + ' died');
      });
    } else {
      // Worker processes have a http server.
      http.Server(function(req, res) {
        res.writeHead(200);
        res.end("hello world\n");
      }).listen(8000);
    }
    

    As you can see in the code above, you should use as many forks as the number of cpus you have, so that all cores work in the same time (distribute the work between your processor's cores).

提交回复
热议问题