Node.js on multi-core machines

前端 未结 15 1492
猫巷女王i
猫巷女王i 2020-11-22 07:46

Node.js looks interesting, BUT I must miss something - isn\'t Node.js tuned only to run on a single process and thread?

Then how does it scale for m

15条回答
  •  独厮守ぢ
    2020-11-22 08:28

    You can use cluster module. Check this.

    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('exit', function(worker, code, signal) {
            console.log('worker ' + worker.process.pid + ' died');
        });
    } else {
        // Workers can share any TCP connection
        // In this case its a HTTP server
        http.createServer(function(req, res) {
            res.writeHead(200);
            res.end("hello world\n");
        }).listen(8000);
    }
    

提交回复
热议问题