Created
July 11, 2024 02:39
-
-
Save kevboutin/ca70fc33369676287aed048c455edbea to your computer and use it in GitHub Desktop.
Worker thread example
This file contains hidden or 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
/* 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