Skip to content

Instantly share code, notes, and snippets.

@peterkingsbury
Created April 6, 2020 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterkingsbury/2273ff362db5d53fc64e50ffda58f480 to your computer and use it in GitHub Desktop.
Save peterkingsbury/2273ff362db5d53fc64e50ffda58f480 to your computer and use it in GitHub Desktop.
'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