Last active
June 29, 2018 08:11
-
-
Save deleteman/8e0c6d51c6875e1fc0e147c31e1d6897 to your computer and use it in GitHub Desktop.
This file contains 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'); | |
const request = require("request"); | |
function startWorker(path, cb) { | |
let w = new Worker(path, {workerData: null}); | |
w.on('message', (msg) => { | |
cb(null, msg) | |
}) | |
w.on('error', cb); | |
w.on('exit', (code) => { | |
if(code != 0) | |
console.error(new Error(`Worker stopped with exit code ${code}`)) | |
}); | |
return w; | |
} | |
console.log("this is the main thread") | |
let myWorker = startWorker(__dirname + '/workerCode.js', (err, result) => { | |
if(err) return console.error(err); | |
console.log("[[Heavy computation function finished]]") | |
console.log("First value is: ", result.val); | |
console.log("Took: ", (result.timeDiff / 1000), " seconds"); | |
}) | |
const start = Date.now(); | |
request.get('http://www.google.com', (err, resp) => { | |
if(err) { | |
return console.error(err); | |
} | |
console.log("Total bytes received: ", resp.body.length); | |
//myWorker.postMessage({finished: true, timeDiff: Date.now() - start}) //you could send messages to your workers like this | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment