node js test cluster

var cluster = require(‘cluster‘);
var http = require(‘http‘);
var fs = require("fs");
//var process = require("process");
var num = require("os").cpus().length;

if (cluster.isMaster) {
    if (fs.existsSync("aa.txt")) {
        fs.unlinkSync("aa.txt");
    }
    // Fork workers.
    for (var i = 0; i < num; i++) {
        //console.log("fork " + i);
        var worker = cluster.fork();
        worker.on("message", function(msg) {
            finish++;
            if (finish == 8) {
                console.log("all done.");
            }
            this.kill();
        });

    }

    var finish = 0;

    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
    /*    console.log("start http server @ " + cluster.worker.process.pid);
    http.createServer(function(req, res) {
        console.log("request @ " + cluster.worker.process.pid);
        res.writeHead(200);
        setTimeout(function() {
            res.end("hello world\n @ " + cluster.worker.process.pid);
        }, 20000);
        var i = 9999999999999;
        while(i-- > 0)
        {

        }
    }).listen(8000);
*/
    var i = 99999;
    var worker = cluster.worker;

    var fd = fs.openSync("aa.txt", "a+");
    //console.log(fd);

    while (i-- > 0) {
        //console.log(i + "@" + worker.process.pid);
        fs.writeSync(fd, i + "@" + worker.process.pid + "\r\n");
    }
    fs.closeSync(fd);
    process.send("ok");
    //worker.kill();
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。