Using worker_threads for Parallel Processing

Node.js 12 introduced the worker_threads module, allowing for parallel execution of JavaScript.

javascriptCopy code// worker.js
const { parentPort } = require('worker_threads');

parentPort.on('message', (data) => {
    // Perform some computation
    parentPort.postMessage(data * 2);
});

// main.js
const { Worker } = require('worker_threads');

function runWorker(data) {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./worker.js');
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.postMessage(data);
    });
}

async function main() {
    try {
        const result = await runWorker(5);
        console.log('Worker result:', result);
    } catch (err) {
        console.error('Worker error:', err);
    }
}

main();

Explanation:

  • worker_threads allows you to create parallel threads for computation.
  • Use postMessage to communicate between the main thread and worker threads.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *