Created
April 6, 2020 17:22
-
-
Save peterkingsbury/2273ff362db5d53fc64e50ffda58f480 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
const assert = require('assert'); | |
const fibonacci = require('fibonacci'); | |
const { | |
Worker, | |
MessageChannel, | |
MessagePort, | |
isMainThread, | |
parentPort, | |
workerData | |
} = require('worker_threads'); | |
if (isMainThread) { | |
const express = require('express'); | |
const app = express(); | |
const port = 3000; | |
app.get('/status', (req, res) => { | |
res.send('OK'); | |
}); | |
app.get('/fibonacci', (req, res) => { | |
const worker = new Worker(__filename, { | |
workerData: { iterations: req.query.iterations || 10 } | |
}); | |
const subChannel = new MessageChannel(); | |
worker.postMessage({ hereIsYourPort: subChannel.port1 }, [ | |
subChannel.port1 | |
]); | |
subChannel.port2.on('message', value => { | |
console.log('received:', value); | |
res.send(value); | |
}); | |
}); | |
app.listen(port, () => { | |
console.log(`FibThreads app listening on port ${port}`); | |
}); | |
} else { | |
parentPort.once('message', value => { | |
console.log(workerData); | |
assert(value.hereIsYourPort instanceof MessagePort); | |
console.log(`Starting Fibonacci sequence with ${workerData.iterations} iterations...`); | |
const result = fibonacci.iterate(workerData.iterations); | |
console.log(`Done (${result.ms} ms)`); | |
value.hereIsYourPort.postMessage(result.number); | |
value.hereIsYourPort.close(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment