Last active
April 7, 2020 07:47
-
-
Save srebalaji/981ff5934b0f472ef2f9a847a60d77f5 to your computer and use it in GitHub Desktop.
NodeJS Worker thread example
This file contains hidden or 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 {Worker, isMainThread, parentPort, workerData} = require('worker_threads') | |
// Returns if the script runs in main thread of in worker | |
if (isMainThread) { | |
const arr = [[1, 10],[2, 15],[3, 21],[4, 25],[5, 86]] | |
for (const ele of arr) { | |
const worker = new Worker(__filename, {workerData: {a: ele[0], b: ele[1]}}) | |
worker.on('message', (result) => { | |
console.log(`The sum of ${ele[0]} and ${ele[1]} is ${result}`) | |
}) | |
worker.on('error', (err) => { | |
console.log(`Some error occured in summing up ${ele[0]} and ${ele[1]}`) | |
}) | |
worker.on('exit', (code) => { | |
// if the returned code is zero, then the worker has closed without any error. So it can be neglected. | |
if (code !== 0) { | |
console.log(`Worker got closed unexpectedly in summing up ${ele[0]} and ${ele[1]} with code ${code}`) | |
} | |
}) | |
} | |
} else { | |
parentPort.postMessage(workerData.a + workerData.b) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment