Worker Threads in nodejs

Worker threads allow the execution of JavaScript in parallel on multiple threads. This is useful for CPU-intensive tasks that would otherwise block the event loop. Workers share memory using SharedArrayBuffer.

Example

const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
  const worker = new Worker(__filename);
} else {
  parentPort.postMessage('Hello from worker');
}

A simple worker thread example showing communication between the main thread and the worker.