Created
January 19, 2019 14:26
-
-
Save liron-navon/c68274b54d1da98a85e03d8717155faf to your computer and use it in GitHub Desktop.
Worker threads 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 { 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