Worker Threads chạy JS trong separate threads trong cùng process — chia sẻ memory qua SharedArrayBuffer, dùng Atomics để synchronize.
- Cluster tạo separate OS processes — không share memory, overhead IPC cao hơn.
- Worker Threads API:
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads'). - Main thread:
new Worker('./worker.js', { workerData: { input } }), lắng ngheworker.on('message', result => ...). - Worker thread:
parentPort.postMessage(result). - Message passing qua
postMessage()— data được structured clone (deep copy) trừ khi transfer ownership với Transferable (ArrayBuffer). - SharedArrayBuffer + Atomics: chia sẻ raw memory không cần copy — dùng cho real-time collaboration, game state.
- Use cases thực tế: image resizing (sharp library), PDF generation, crypto operations, ML inference, large JSON parsing.
- Lưu ý: Worker Threads không tăng tốc I/O-bound tasks — Node.js event loop đã xử lý I/O async; chỉ dùng cho CPU-bound tasks chiếm event loop > 10ms.
Worker Threads run JavaScript in separate threads within the same process — sharing memory via SharedArrayBuffer, with synchronization using Atomics.
- Cluster creates separate OS processes — no shared memory, and IPC overhead is higher.
- Worker Threads API:
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads'). - Main thread:
new Worker('./worker.js', { workerData: { input } }), listens withworker.on('message', result => ...). - Worker thread:
parentPort.postMessage(result). - Message passing via
postMessage()— data is structured-cloned (deep copy) unless ownership is transferred with a Transferable (ArrayBuffer). - SharedArrayBuffer + Atomics: shares raw memory without copying — useful for real-time collaboration, game state.
- Real use cases: image resizing (sharp), PDF generation, crypto operations, ML inference, large JSON parsing.
Pitfall: Worker Threads don't speed up I/O-bound tasks — Node.js event loop already handles I/O asynchronously; only use them for CPU-bound tasks that block the event loop for more than 10ms.