Skip to content

Instantly share code, notes, and snippets.

@myesn
Last active December 21, 2021 03:31
Show Gist options
  • Save myesn/599b0f04f94fc40f70f50ed2a11073a6 to your computer and use it in GitHub Desktop.
Save myesn/599b0f04f94fc40f70f50ed2a11073a6 to your computer and use it in GitHub Desktop.
node.js 利用所有的 CPU 内核
const express = require('express');
const os = require('os');
const cluster = require('cluster');
const app = express();
const PORT = process.env.PORT || 5000;
const clusterWorkerSize = os.cpus().length;
if (clusterWorkerSize > 1) {
if (cluster.isMaster) {
for (let i = 0; i < clusterWorkerSize; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log('Worker', worker.id, ' has exitted.');
});
} else {
app.listen(PORT, () => {
console.log(
`Express server listening on port ${PORT} and worker ${process.pid}`
);
});
}
} else {
app.listen(PORT, () => {
console.log(
`Express server listening on port ${PORT} with the single worker ${process.pid}`
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment