Say my pc has a cpu with 2 cores, and my node.js application using express. How can i run this application on 1 core and this same application on the other core?
Nicovank
is right. You are interested in feature called cluster
. In nodejs you getting number of cores by this code:
const numCPUs = require('os').cpus().length;
Please refer to this section of documentation: https://nodejs.org/dist/latest-v7.x/docs/api/cluster.html#cluster_cluster . The have great examples.
Here's a basic example of an express server running in multiple cores using the cluster module.
const cluster = require('cluster');
//Get number of CPUs
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork one worker per core.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
//Worker code...
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// Bind to a port
app.listen(8080, () => {
console.log(`[PID=${process.pid}] server started!`);
});
}
There are some third party modules too:
You can also check:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.