Skip to content

Instantly share code, notes, and snippets.

@deleteman
Created June 22, 2018 05:24
Show Gist options
  • Save deleteman/c31a9704f9cbe3b15c45bb439a4c0da2 to your computer and use it in GitHub Desktop.
Save deleteman/c31a9704f9cbe3b15c45bb439a4c0da2 to your computer and use it in GitHub Desktop.
Example of using worker threads for heavy computation while performing async operation
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const request = require("request");
if(isMainThread) {
console.log("This is the main thread")
let w = new Worker(__filename, {workerData: null});
w.on('message', (msg) => { //A message from the worker!
console.log("First value is: ", msg.val);
console.log("Took: ", (msg.timeDiff / 1000), " seconds");
})
w.on('error', console.error);
w.on('exit', (code) => {
if(code != 0)
console.error(new Error(`Worker stopped with exit code ${code}`))
});
request.get('http://www.google.com', (err, resp) => {
if(err) {
return console.error(err);
}
console.log("Total bytes received: ", resp.body.length);
})
} else { //the worker's code
function random(min, max) {
return Math.random() * (max - min) + min
}
const sorter = require("./test2-worker");
const start = Date.now()
let bigList = Array(1000000).fill().map( (_) => random(1,10000))
sorter.sort(bigList);
parentPort.postMessage({ val: sorter.firstValue, timeDiff: Date.now() - start});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment