Skip to content

Instantly share code, notes, and snippets.

@liron-navon
Created January 19, 2019 14:26
Show Gist options
  • Select an option

  • Save liron-navon/c68274b54d1da98a85e03d8717155faf to your computer and use it in GitHub Desktop.

Select an option

Save liron-navon/c68274b54d1da98a85e03d8717155faf to your computer and use it in GitHub Desktop.
Worker threads example
const { parentPort, workerData, isMainThread } = require("worker_threads");
// CPU consuming function (sorting a big array)
function sortBigArray(bigArray) {
return bigArray.sort((a, b) => a - b);
}
// check that the sorter was called as a worker thread
if (!isMainThread) {
// make sure we got an array of data
if (!Array.isArray(workerData)) {
// we can throw an error to emit the "error" event from the worker
throw new Error("workerData must be an array of numbers");
}
// we post a message through the parent port, to emit the "message" event
parentPort.postMessage(sortBigArray(workerData));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment