Skip to content

Instantly share code, notes, and snippets.

@shubham-sharmas
Created November 16, 2023 18:47
Show Gist options
  • Save shubham-sharmas/ea7578c1e899f10846edf00048b7a270 to your computer and use it in GitHub Desktop.
Save shubham-sharmas/ea7578c1e899f10846edf00048b7a270 to your computer and use it in GitHub Desktop.
This gist demonstrates the node.js worker threads example by simulating a time-consuming task.
const { Worker, isMainThread, parentPort } = require("worker_threads");
if (isMainThread) {
console.log("Main thread started.");
// Create a new worker thread
const worker = new Worker(__filename);
// Listen for messages from the worker thread
worker.on("message", (result) => {
console.log("Result from worker:", result);
// Terminate the worker thread
worker.terminate();
console.log("Main thread finished.");
});
} else {
// Worker thread logic
console.log("Worker thread started.");
// Simulate a time-consuming task
const simulateTask = () => {
console.log("simulateTask ~ simulating a long running task");
const startTime = Date.now();
let result = [];
for (let i = 0; i < 300000; i++) {
result.unshift(i);
}
return {
result,
totalExecutionTime: `${(Date.now() - startTime) / 1000} seconds`,
};
};
// Perform the time-consuming task
const result = simulateTask();
// Send the result back to the main thread
parentPort.postMessage(result);
console.log("Worker thread finished.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment