The node:worker_threads module enables true parallel execution of CPU-heavy tasks (such as image manipulation, matrix calculations, or cryptography) on separate threads without blocking the main event loop thread.
flowchart LR
A["Main Thread (Event Loop)"] -->|"Worker Thread Spawning"| B["Worker Thread Instance"]
A -->|"parentPort.postMessage(data)"| B
B -->|"parentPort.postMessage(result)"| A
A <-->|"SharedArrayBuffer"| B
// worker_app.js - Main Thread & Worker logic combined via isMainThread
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
if (isMainThread) {
console.log(`[Main Thread PID ${process.pid}] Dispatching heavy CPU computation task...`);
const worker = new Worker(__filename, {
workerData: { iterations: 1_000_000_000 }
});
worker.on('message', (result) => {
console.log(`[Main Thread] Calculation complete! Sum: ${result.totalSum}`);
});
worker.on('error', (err) => console.error('[Worker Error]:', err));
worker.on('exit', (code) => console.log(`Worker exited with code ${code}`));
} else {
// Inside Worker Thread Execution Context
const { iterations } = workerData;
let sum = 0;
for (let i = 0; i < iterations; i++) {
sum += i;
}
// Send result back to Main Thread
parentPort.postMessage({ totalSum: sum });
}
piscina) for recurring tasks.SharedArrayBuffer for Large Data Transfers: Transferring large payloads serializes data; use SharedArrayBuffer or ArrayBuffer transfer lists for zero-copy memory transfers.How does data sharing differ between child_process.fork() and worker_threads?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.