Lab 04: Worker Threads Advanced

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm node:20-alpine sh

Node.js is single-threaded by default, but worker_threads enables true parallelism for CPU-bound tasks. This lab covers SharedArrayBuffer, Atomics, zero-copy transfers, and building a thread pool.


Step 1: Worker Threads Architecture

Main Thread

├── Worker 1 (own V8 isolate + libuv event loop)
├── Worker 2 (own V8 isolate + libuv event loop)
├── Worker 3 (own V8 isolate + libuv event loop)
└── Worker 4 (own V8 isolate + libuv event loop)

Communication:
  - MessageChannel: structured clone (copy)
  - SharedArrayBuffer: true shared memory (zero-copy)
  - transferList: transfer ownership (zero-copy, original invalidated)

Workers have their own V8 heap but can share memory via SharedArrayBuffer.


Step 2: Basic Worker with workerData

💡 workerData is deep-cloned via structured clone algorithm. Use SharedArrayBuffer for large data to avoid copying.


Step 3: SharedArrayBuffer + Atomics

SharedArrayBuffer provides memory shared between threads. Atomics ensures thread-safe operations:

Run: node shared-counter.mjs

📸 Verified Output:

💡 Without Atomics.add, concurrent arr[0]++ would lose updates (race condition). Atomics prevents this with CPU-level memory ordering.


Step 4: Atomics.wait / Atomics.notify (Mutex Pattern)


Step 5: Zero-Copy Transfer with transferList

💡 transferList moves the buffer's backing memory to the other thread. The original ArrayBuffer becomes detached (byteLength = 0). Great for image/audio processing pipelines.


Step 6: MessageChannel for Direct Worker-to-Worker Communication


Step 7: Thread Pool Pattern


Step 8: Capstone — CPU-Bound Parallelism Benchmark


Summary

API
Description
Use Case

new Worker(filename)

Spawn worker thread

CPU-bound parallelism

workerData

Pass data at creation

Initial config, immutable

parentPort.postMessage

Send structured-clone

General message passing

SharedArrayBuffer

Shared memory

Zero-copy high-frequency updates

Atomics.add/sub

Atomic arithmetic

Thread-safe counters

Atomics.compareExchange

CAS operation

Mutex/lock implementation

Atomics.wait/notify

Thread synchronization

Blocking wait / wake

transferList

Transfer ownership

Large buffers, zero-copy

MessageChannel

Worker-to-worker pipe

Direct inter-worker comms

Last updated