For years, critics claimed Node.js was unsuitable for CPU-heavy tasks because of its single-threaded nature. Introduced natively in modern Node.js, the worker_threads module provides true multi-threaded JavaScript execution by running multiple Node.js event loops and V8 isolates inside a single OS process.
// primeWorker.js
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
if (isMainThread) {
// 1. MAIN THREAD LOGIC
console.log('[Main Thread] Spawning background worker thread...');
const worker = new Worker(__filename, {
workerData: { start: 2, end: 10000000 } // Pass data to worker
});
// Receive messages from worker
worker.on('message', (result) => {
console.log(`[Main Thread] Found ${result.primeCount} primes in ${result.duration}ms!`);
});
worker.on('error', (err) => console.error('[Worker Error]', err));
worker.on('exit', (code) => console.log(`Worker thread exited with code ${code}`));
console.log('[Main Thread] Non-blocking! Can still accept incoming HTTP requests.');
} else {
// 2. BACKGROUND WORKER THREAD LOGIC
const { start, end } = workerData;
const startTime = Date.now();
function isPrime(num) {
for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
if (num % i === 0) return false;
}
return num > 1;
}
let count = 0;
for (let i = start; i < end; i++) {
if (isPrime(i)) count++;
}
const duration = Date.now() - startTime;
// Send result back to the main thread
parentPort.postMessage({ primeCount: count, duration });
}
SharedArrayBuffer & AtomicsNormally, message passing between threads serializes data (structured cloning). With SharedArrayBuffer, both threads read and mutate the exact same memory without any copy overhead:
// Allocate a 4-byte shared buffer for a 32-bit integer
const sharedBuffer = new SharedArrayBuffer(4);
const sharedArray = new Int32Array(sharedBuffer);
// Thread-safe atomic increment (prevents race conditions)
Atomics.add(sharedArray, 0, 1);
console.log('Thread-safe atomic value:', Atomics.load(sharedArray, 0));
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Compare worker threads with heavy OS processes.
Clustering for network I/O vs workers for CPU.
Measure thread pool efficiency.