Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created July 11, 2024 02:39
Show Gist options
  • Save kevboutin/ca70fc33369676287aed048c455edbea to your computer and use it in GitHub Desktop.
Save kevboutin/ca70fc33369676287aed048c455edbea to your computer and use it in GitHub Desktop.
Worker thread example
/* This code creates a worker thread from the “long_calculation.js” file. The main
* thread sends data to the worker, which performs the calculation and returns the
* result via the “ message ” event. This approach keeps your main thread responsive
* while intensive tasks run in the background.
*/
const { Worker } = require('worker_threads');
const worker = new Worker('./long_calculation.js');
worker.on('message', (result) => {
console.log('Calculation result:', result);
});
worker.postMessage({ data: [1, 2, 3, 4, 5] });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment