码迷,mamicode.com
首页 > Web开发 > 详细

node js test cluster

时间:2015-03-03 20:34:40      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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();
}

 

node js test cluster

标签:

原文地址:http://www.cnblogs.com/eturn/p/4311661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!