Skip to content

Instantly share code, notes, and snippets.

@SK-CSE
Created September 26, 2020 09:43
Show Gist options
  • Save SK-CSE/da9b2322d86d2a1bfd9c320a7268006d to your computer and use it in GitHub Desktop.
Save SK-CSE/da9b2322d86d2a1bfd9c320a7268006d to your computer and use it in GitHub Desktop.
worker thread demo
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