Multi threading with hyper-express #78
-
Hi there, I wanted to run multiple child processes which each handle requests by their own to parallelize the workload, however no matter what i do (used workerpools, used child processes), i can't seem to do it. Has anyone else done it before and would be willing to help me? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I'm not sure what exact problem you are having but you can simply use the // NOTE: Any global code/variables will be executed for both the master and forked worker processes
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const HyperExpress = require('hyper-express');
// Check if the current process is the master process
if (cluster.isPrimary) {
// NOTE: Code inside of this block will only run ONCE in the master/primary process
// Spawn the initial set of worker instances which will be decided based on the number of cpu cores available
for (let i = 0; i < numCPUs; i++) cluster.fork();
} else {
// NOTE: Code inside of this block will run for each time a worker is forked with the fork() method from the master process.
// Initialize the HyperExpress server instance
const server = new HyperExpress.Server();
// Bind a test route which will return the process id in which it is serving the request from
server.get('/id', (request, response) => {
response.send('Served this request from ' + process.pid);
});
// Listen the server on the desired port
server.listen(3000);
} If you make a bunch of requests to the |
Beta Was this translation helpful? Give feedback.
-
I'm having the same issue (but on macOS). If I start a plain express server in my cluster script, the requests get distributed perfectly. If I start a hyper-express server, all requests always go to the same thread. |
Beta Was this translation helpful? Give feedback.
I'm not sure what exact problem you are having but you can simply use the
cluster
module in Node.js to multi-thread HyperExpress instances to have them handle their own payloads similar to all other webservers. Below is an example code snippet to do this with some usage comments: