Created
April 7, 2020 14:25
-
-
Save srebalaji/50c3da4fabcd436eadabbb30b02861bf to your computer and use it in GitHub Desktop.
Message channels between 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
// main.js | |
const {Worker, parentPort, MessageChannel} = require('worker_threads') | |
const worker = new Worker('./worker.js') | |
const messageChannel = new MessageChannel() | |
// As you can see there are two parameters passed in `postMessage` | |
worker.postMessage({yourPort: messageChannel.port1}, [messageChannel.port1]) | |
const arr = [[1, 10],[2, 15],[3, 21],[4, 25],[5, 86]] | |
for (const ele of arr) { | |
messageChannel.port2.postMessage({input: ele}) | |
} | |
messageChannel.port2.on('message', (msg) => { | |
console.log(msg.output) | |
}) | |
// worker.js | |
const { parentPort, workerData } = require('worker_threads') | |
parentPort.on('message', (value) => { | |
const {yourPort} = value | |
yourPort.addListener('message', handleInput) | |
}) | |
function handleInput(data) { | |
const {input} = data | |
this.postMessage({output: `The sum of ${input[0]} and ${input[1]} is ${input[0] + input[1]}`}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment