Last active
October 9, 2020 15:49
-
-
Save Kannndev/574f4795570866ba2c9667370012fca9 to your computer and use it in GitHub Desktop.
Node non blocking using workers
This file contains 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 express = require('express'); | |
const { Worker } = require('worker_threads'); | |
const app = express(); | |
app.get('/', function (req, res) { | |
const worker = new Worker(__dirname + '/worker.js', { | |
workerData: { ping: 'pong' }, | |
}); | |
worker.on('message', (pi) => { | |
res.send(`Pi Value, ${pi}`); | |
}); | |
worker.on('error', (err) => { | |
res.status({ status: 500 }).json({ message: err.message }); | |
}); | |
worker.on('exit', (code) => { | |
if (code !== 0) { | |
res.status({ status: 500 }).json({ message: code }); | |
} | |
}); | |
worker.postMessage('getMeThePiValue'); | |
}); | |
app.get('/hello', function (req, res) { | |
res.send(`hello world`); | |
}); | |
app.listen(3000); |
This file contains 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 { parentPort, workerData } = require('worker_threads'); | |
function getPi() { | |
let sum = 0; | |
for (let n = 0; n < 10000000000; n++) { | |
let mult = n % 2 === 0 ? 1 : -1; | |
sum += mult * (1 / (2 * n + 1)); | |
} | |
return sum * 4; | |
} | |
parentPort.on('message', (param) => { | |
console.log(param); // getMeThePiValue | |
console.log(workerData); // { ping: 'pong'} | |
const pi = getPi(); | |
parentPort.postMessage(pi); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment