Created
September 26, 2020 09:43
-
-
Save SK-CSE/da9b2322d86d2a1bfd9c320a7268006d to your computer and use it in GitHub Desktop.
worker thread demo
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'); | |
if(isMainThread) { | |
console.log('main thread start...'); | |
const worker = new Worker(__filename, { | |
workerData: { | |
prefix: 'Received message', | |
timeInSecond: 1000 | |
} | |
}); | |
worker.on('message', (msg) => { | |
console.log(`Worker: ${msg}`); | |
}); | |
worker.postMessage('Done with my work.'); | |
console.log("doing some random work in main thread..!!"); | |
} else { | |
parentPort.on('message', (msg) => { | |
console.log(`${workerData.prefix}: ${msg}`); | |
}); | |
parentPort.postMessage('hello from worker thread'); | |
cpuIntensiveTask(workerData.timeInSecond); | |
parentPort.postMessage('i am working'); | |
cpuIntensiveTask(workerData.timeInSecond); | |
parentPort.postMessage('task is done..!!'); | |
} | |
function cpuIntensiveTask(timeInSecond) { | |
const end = Date.now() + timeInSecond; | |
while (Date.now() < end) { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment