Worker Threads
Worker Threads allow JavaScript execution to occur in separate threads. They are useful for CPU-intensive work that would otherwise block the event loop.
Workers communicate through message passing and can optionally share memory through SharedArrayBuffer and synchronization primitives.
Basic Worker Thread
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
worker.on('message', console.log);
worker.postMessage(10);
} else {
parentPort.on('message', (value) => {
parentPort.postMessage(value * value);
});
}💡 The main thread creates a worker and sends it data. The worker performs CPU work and sends the result back.
Key Takeaways
- Worker Threads are useful for CPU-intensive JavaScript.
- Workers prevent CPU-heavy calculations from monopolizing the main event loop.
- Worker creation and communication have overhead, so workloads should justify their use.
Knowledge Check
When are Worker Threads most useful?