2

Does the latest Node.js version(4.2.3) supports multi threading now? Hard to find useful answers as most relevant discussions are from years ago.

How would a node.js cloud server handle node.js Web App requests? Say a 2-Core server runs a node.js app, does that mean no matter how heavy the traffic is, they all go through via a single core and the other core is always idle?

If the answer is yes, any recommendations of some third party libs could possibly achieve multi-threading for node.js Web Apps?


Thanks for the helps. In addition to the above question. I adopted the cluster code into an Express.js web app, it turns out the else block is not executed in the below code section. var app = require('../app'); var debug = require('debug')('NewExpress:server'); var http = require('http'); var cluster = require('cluster'); 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 {

    /**
     * Get port from environment and store in Express.
     */

    var port = normalizePort(process.env.PORT || '3000');
    app.set('port', port);

    /**
     * Create HTTP server.
     */

    var server = http.createServer(app);

    /**
     * Listen on provided port, on all network interfaces.
     */

    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);
}

Any ideas how should I implement cluster in here?

JunglerSens
  • 200
  • 1
  • 15
  • 1
    [Clusters](https://nodejs.org/dist/latest-v5.x/docs/api/cluster.html). Regarding multi-threading, Node.js doesn't fit well into a simple "yes or no." It has always made use of multiple threads. It however only uses one of them with the v8 engine for executing JavaScript code. The other threads can be utilized by native extensions for performing the bulk of asynchronous I/O. – Jonathan Lonowski Dec 19 '15 at 02:04

1 Answers1

1

You can use each of your cpus like this:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  startServer();
}

Update

To give a fuller example, you can throw this in index.js:

var express = require('express');
var app = express();
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  startServer();
}

function startServer() {
  var server = app.listen(3000, function () {
      var port = server.address().port;
      console.log('Example app listening at %s', port);
    });
}

run node index.js in a terminal to start it up. and it will log this with my 8 cpu monster:

Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000

Update 2

After seeing the question edit, I adapted your example. This should work

var http = require('http');
var express = require('express');
var app = express();
var cluster = require('cluster');
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 {
    console.log('in else statement');
    var port = '3000';
    app.set('port', port);
    var server = http.createServer(app);
    server.listen(port);
}

and it should show this in the console

in else statement
in else statement
in else statement
in else statement
in else statement
in else statement
in else statement
in else statement

Let me know if this is not running for you.

curtwphillips
  • 5,441
  • 1
  • 20
  • 19
  • A further question in related to the above code. I am using Express.js to build a web app. However when I tried to adopt the above code, the else block seems wasn't executed. Could you help me to have a check? Thanks in advance. – JunglerSens Dec 19 '15 at 03:02
  • Thanks Curt. I've tested in many ways and realises it works perfectly when I hit 'Run' in WebStorm but not 'Debug' mode. So I suppose I need to comment out the cluster relevant code in dev environment. – JunglerSens Dec 19 '15 at 07:53
  • 1
    If you comment it out or you will have to remember to uncomment it before you deploy. I'm not familiar with webstorm, but maybe try setting an environmental variable for your node process on your local machine. If you are on mac, add something like 'export NODE_ENV=dev' to your .bash_profile. That way you can use " If process.env.NODE_ENV != 'dev' ... to make the cluster run when not on your dev environment. If you're on windows try " SET NODE_ENV=dev". I'm not sure how to persist it on Windows off the top of my head. – curtwphillips Dec 21 '15 at 20:42