Worker threads 让 Node 在独立线程上运行 JavaScript,具有真正的并行性——解决了 Node 的最大限制:CPU 密集型工作会阻塞单个主线程(从而阻塞所有请求)。将其用于繁重计算,而不是用于 I/O(event loop 已经高效处理)。
它们解决的问题
js
app.(, {
result = ();
res.(result);
});
Worker threads 让 Node 在独立线程上运行 JavaScript,具有真正的并行性——解决了 Node 的最大限制:CPU 密集型工作会阻塞单个主线程(从而阻塞所有请求)。将其用于繁重计算,而不是用于 I/O(event loop 已经高效处理)。
app.(, {
result = ();
res.(result);
});
Node 在一个线程上运行您的 JS。一个长时间的同步计算会阻塞一切 —— event loop 在其完成之前无法处理其他请求。Worker threads 将该工作从主线程移开。
// main.js
import { Worker } from "worker_threads";
function runHeavyTask(data) {
return new Promise((resolve, reject) => {
const worker = new Worker("./worker.js", { workerData: data }); // runs on a NEW thread
worker.on("message", resolve); // receive the result
worker.on("error", reject);
worker.on("exit", (code) => { if (code !== 0) reject(new Error(`exit ${code}`)); });
});
}
// the main thread stays free to handle other requests while this runs
const result = await runHeavyTask({ numbers: [...] });
// worker.js — runs in parallel, on its own thread
import { workerData, parentPort } from "worker_threads";
const result = expensiveComputation(workerData); // doesn't block the main thread
parentPort.postMessage(result); // send the result back
Worker 独立运行;主线程继续处理请求,在完成时通过消息获得结果。
✓ USE for CPU-bound work: image/video processing, encryption, compression,
big data parsing, complex calculations, ML inference
✗ DON'T use for I/O (DB, files, HTTP) — the async event loop already handles
that efficiently; a worker would add overhead for no benefit
规则:workers 用于 CPU 密集,event loop 用于 I/O 密集。
worker_threads → share memory (efficient data passing), in-process threads — CPU work
child_process → separate OS processes, run other programs — heavier isolation
cluster → fork the whole server across CPUs — scale request handling
Worker threads 解决了 Node 的核心弱点——CPU 密集任务阻塞单线程 event loop 并冻结所有并发请求。
知道何时将繁重计算卸载到 worker(保持主线程响应),以及最关键的是何时使用它们(仅限 CPU 密集,I/O 永不使用),这是让 Node 服务能够处理偶尔的繁重处理而不牺牲使 Node 有价值的并发性的关键。
对于生产环境中的 worker 池管理,Piscina 等库可以高效地管理线程池。