Skip to content

Instantly share code, notes, and snippets.

@srebalaji
Created April 7, 2020 14:25
Show Gist options
  • Save srebalaji/50c3da4fabcd436eadabbb30b02861bf to your computer and use it in GitHub Desktop.
Save srebalaji/50c3da4fabcd436eadabbb30b02861bf to your computer and use it in GitHub Desktop.
Message channels between workers
// 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