</>
⌕
Senior #worker_threads#cluster#child_process#concurrency

worker_threads, cluster và child_process khác nhau thế nào?

⚡ Trả lời nhanh

worker_threads: thread trong cùng process, có V8 isolate riêng, chia sẻ memory qua SharedArrayBuffer, hợp tác vụ CPU nặng. cluster: nhiều process Node cùng lắng nghe một port để tận dụng nhiều core. child_process: chạy process/chương trình bên ngoài, giao tiếp qua IPC hoặc stdio.

worker_threadsclusterchild_process
Đơn vịThreadProcess (fork của chính app)Process bất kỳ
Bộ nhớRiêng, có thể share SharedArrayBufferRiêng hoàn toànRiêng hoàn toàn
Giao tiếppostMessageIPCIPC / stdio
Dùng choCPU-bound (nén, hash, parse lớn)Scale HTTP server theo coreChạy ffmpeg, script, lệnh shell
Chi phíNhẹ hơn processNặng (mỗi worker một runtime)Nặng
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

if (isMainThread) {
  const w = new Worker(new URL(import.meta.url), { workerData: 40 });
  w.on("message", r => console.log("fib =", r));
} else {
  const fib = n => (n < 2 ? n : fib(n - 1) + fib(n - 2));
  parentPort.postMessage(fib(workerData));
}
🃏 Ôn bằng flashcard