Created
November 6, 2019 11:52
-
-
Save simonespa/bc52b55757ecf39271d6e45968964fd7 to your computer and use it in GitHub Desktop.
NodeJS clustering with message passing from master to workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const cluster = require('cluster'); | |
| const numCPUs = require('os').cpus().length; | |
| const express = require('express') | |
| const app = express(); | |
| const port = 3000; | |
| app.get('/', (req, res) => res.send('Hello World!')); | |
| if (cluster.isMaster) { | |
| console.log(`Master ${process.pid} is running`); | |
| // Fork workers. | |
| for (let i = 0; i < numCPUs; i++) { | |
| const worker = cluster.fork(); | |
| worker.send('hey there'); | |
| } | |
| cluster.on('exit', (worker, code, signal) => { | |
| console.log(`worker ${worker.process.pid} died`); | |
| }); | |
| } else { | |
| process.on('message', (message) => { | |
| console.log(`Worker ${process.pid} received a message from master: ${message}`); | |
| }); | |
| app.listen(port, () => { | |
| console.log(`Example app listening on port ${port}!`) | |
| }); | |
| console.log(`Worker ${process.pid} started`); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment