Node.js 中遇到 CPU 密集型任务时,worker_threads 到底该怎么用?
有一次接口响应突然从 30ms 涨到 2s,排查后发现是一个看似普通的图片元数据解析接口在作祟。这类接口里藏着同步的解析逻辑,单次处理几百 KB 图片时 CPU 占用直接拉满,Node.js 主线程被卡住,所有后续请求都在排队。类似场景还有敏感词匹配、大型 JSON 格式化、加解密、PDF 内容提取等,它们共同点是计算时间长、几乎不涉及 I/O。把这类任务放在主线程,事件循环就没机会处理其他回调,表现为服务整体吞吐骤降。worker_threads 是 Node.js 官方给出的解决办法,能让这些计算跑在独立线程里,但线程创建、数据传递、异常处理都有讲究,用错了反而更慢。这篇文章结合实际代码,聊聊 worker_threads 的适用边界、通信成本、线程池复用,以及和 child_process、cluster 的取舍。 ## 一个问题接口长什么样 假设有一个处理日志文件的接口,需要读取用户上传的日志文本,统计其中某个关键字出现的次数,并返回频次最高的前十个匹配行。最初实现可能是这样的: ```js // server.js const express = require('express'); const app = express(); app.use(express.text({ limit: '10mb' })); app.post('/analyze', (req, res) => { const content = req.body; const keyword = req.query.keyword || 'error'; const lines = content.split('\n'); const counter = new Map(); for (const line of lines) { if (line.includes(keyword)) { counter.set(line, (counter.get(line) || 0) + 1); } } const top = [...counter.entries()] .sort((a, b) => b[1] - a[1]) .slice(0, 10); res.json({ total: counter.size, top }); }); ``` 当请求体达到 5MB、行数十几万时,`split`、循环和 `sort` 都是同步操作,主线程被占满。压测下并发 10 个请求,事件循环延迟能到秒级,健康检查也会超时。 ## worker_threads 的基础用法 Node.js 10 开始引入 worker_threads,12 之后逐渐稳定。每个 worker 有独立的 V8 实例和事件循环,适合执行纯计算任务。把上面的分析逻辑搬到 worker 中: ```js // analyzer.js const { parentPort } = require('worker_threads'); parentPort.on('message', ({ content, keyword }) => { const lines = content.split('\n'); const counter = new Map(); for (const line of lines) { if (line.includes(keyword)) { counter.set(line, (counter.get(line) || 0) + 1); } } const top = [...counter.entries()] .sort((a, b) => b[1] - a[1]) .slice(0, 10); parentPort.postMessage({ total: counter.size, top }); }); ``` 主线程改为创建 worker 并等待结果: ```js const { Worker } = require('worker_threads'); function analyze(content, keyword) { return new Promise((resolve, reject) => { const worker = new Worker('./analyzer.js'); worker.once('message', resolve); worker.once('error', reject); worker.postMessage({ content, keyword }); }); } app.post('/analyze', async (req, res) => { const result = await analyze(req.body, req.query.keyword || 'error'); res.json(result); }); ``` 这样主线程只负责接收请求和转发数据,计算都在 worker 里。不过每次请求都 new Worker 的代价不小,官方文档提到启动一个 worker 大约需要几十毫秒,频繁创建会拖慢响应。 ## 线程池与复用 实际服务里通常用一个简单的线程池,把 worker 保持在固定数量,任务排队执行。社区有 `piscina` 这类库,但如果不想引依赖,也可以自己搭一个最小可用的池子: ```js // pool.js const { Worker } = require('worker_threads'); const os = require('os'); const workers = []; const queue = []; let nextId = 0; const WORKER_COUNT = Math.max(2, os.cpus().length - 1); for (let i = 0; i { const task = worker.currentTask; worker.busy = false; worker.currentTask = null; task.resolve(msg); dispatch(); }); worker.on('error', (err) => { if (worker.currentTask) { worker.currentTask.reject(err); worker.currentTask = null; } worker.busy = false; dispatch(); }); workers.push(worker); } function dispatch() { if (queue.length === 0) return; const worker = workers.find((w) => !w.busy); if (!worker) return; const task = queue.shift(); worker.busy = true; worker.currentTask = task; worker.postMessage(task.payload); } function run(payload) { return new Promise((resolve, reject) => { queue.push({ payload, resolve, reject }); dispatch(); }); } module.exports = { run }; ``` 接口层改成 `pool.run({ content, keyword })`。这里有几个细节要注意: - `analyzer.js` 里的 `parentPort.on('message')` 可以处理多次消息,所以 worker 能持续复用; - 错误处理要区分 `error` 和 `exit`,如果 worker 因为未捕获异常退出,池子需要重建该 worker; - `os.cpus().length - 1` 是为了给主线程留出核心,但如果是 I/O 密集服务,worker 数量不必按 CPU 核数来。 ## 数据传递不是零成本 `postMessage` 默认使用结构化克隆算法,大对象在传递时会被序列化和反序列化,5MB 的字符串传一次就有明显开销。对于二进制数据,可以用 `ArrayBuffer` 的转移(transfer)来避免拷贝: ```js // 主线程 const buffer = fs.readFileSync('large-file.bin'); const ab = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); worker.postMessage({ ab }, [ab]); ``` 转移后主线程的 `ab` 会被置空,不能再访问。如果数据是多个 worker 共享只读的,`SharedArrayBuffer` 更合适,但它需要配合 `Atomics` 做同步,复杂度较高。多数业务场景下,把数据拆小、减少传递频率比强行共享内存更实际。 ## 哪些任务不该用 worker_threads worker 不是万能加速器。任务本身耗时低于 5ms 时,创建和通信的开销会盖过收益;任务主要是 I/O 等待时,主线程异步就能处理,开 worker 只是多占内存。真正适合的是可并行、计算密集、单次执行超过几十毫秒的任务。 另外,worker 之间不共享 JS 对象,不能直接读写主线程的变量。如果计算依赖大量上下文状态,要么把状态序列化传过去,要么重新设计任务边界。 ## 和 child_process、cluster 的区别 `child_process` 适合需要独立进程、可能执行外部命令或需要内存隔离的场景,比如调用 ffmpeg。进程间通信只能通过管道或 IPC,数据传递比 worker 更重。 `cluster` 解决的是多进程负载均衡,每个进程有独立的事件循环和端口监听,适合把 HTTP 服务横向扩展到多核。它不能把单个请求的计算拆到其他进程里,和 worker_threads 的定位不同。 一个常见的组合是:cluster 启动多个 HTTP 进程,每个进程内部维护自己的 worker 池处理 CPU 任务,这样既用上了多核,又不会因为计算阻塞请求。 ## 调试和监控 worker 里的错误堆栈默认不会带上主线程的调用信息,排查时可以在 worker 内加上 `process.on('uncaughtException')` 记录日志,或者用 `worker.on('error')` 把错误传回主线程。Node.js 的 `--inspect` 对 worker 也支持,Chrome DevTools 里能看到每个 worker 的线程。 线上环境要关注 worker 池的队列长度。如果队列持续增长,说明 worker 数量不够或任务太重;如果 worker 长时间空闲,说明池子开大了。可以用 `perf_hooks` 记录每个任务的执行时间,定期输出到监控系统。 ```js const { performance } = require('perf_hooks'); // 在 worker 内部 parentPort.on('message', (payload) => { const start = performance.now(); const result = doWork(payload); const duration = performance.now() - start; parentPort.postMessage({ result, duration }); }); ``` 主线程拿到 `duration` 后做聚合,就能知道任务分布和是否需要调整池子大小。 推荐查看天气:https://www.0dtq.com/xichong/10tian.html 推荐查看天气:https://www.0dtq.com/xichong/15tian.html 推荐查看天气:https://www.0dtq.com/xichong/40tian.html 推荐查看天气:https://www.0dtq.com/langzhong/ 推荐查看天气:https://www.0dtq.com/langzhong/zuotian.html 推荐查看天气:https://www.0dtq.com/langzhong/7tian.html 推荐查看天气:https://www.0dtq.com/langzhong/10tian.html 推荐查看天气:https://www.0dtq.com/langzhong/15tian.html 推荐查看天气:https://www.0dtq.com/langzhong/40tian.html 推荐查看天气:https://www.0dtq.com/meishan/ 推荐查看天气:https://www.0dtq.com/meishan/zuotian.html 推荐查看天气:https://www.0dtq.com/meishan/7tian.html 推荐查看天气:https://www.0dtq.com/meishan/10tian.html 推荐查看天气:https://www.0dtq.com/meishan/15tian.html 推荐查看天气:https://www.0dtq.com/meishan/40tian.html 推荐查看天气:https://www.0dtq.com/dongpo/ 推荐查看天气:https://www.0dtq.com/dongpo/zuotian.html 推荐查看天气:https://www.0dtq.com/dongpo/7tian.html 推荐查看天气:https://www.0dtq.com/dongpo/10tian.html 推荐查看天气:https://www.0dtq.com/dongpo/15tian.html 推荐查看天气:https://www.0dtq.com/dongpo/40tian.html 推荐查看天气:https://www.0dtq.com/renshou/ 推荐查看天气:https://www.0dtq.com/renshou/zuotian.html 推荐查看天气:https://www.0dtq.com/renshou/7tian.html 推荐查看天气:https://www.0dtq.com/renshou/10tian.html 推荐查看天气:https://www.0dtq.com/renshou/15tian.html 推荐查看天气:https://www.0dtq.com/renshou/40tian.html 推荐查看天气:https://www.0dtq.com/pengshan/ 推荐查看天气:https://www.0dtq.com/pengshan/zuotian.html 推荐查看天气:https://www.0dtq.com/pengshan/7tian.html 推荐查看天气:https://www.0dtq.com/pengshan/10tian.html 推荐查看天气:https://www.0dtq.com/pengshan/15tian.html 推荐查看天气:https://www.0dtq.com/pengshan/40tian.html 推荐查看天气:https://www.0dtq.com/hongya/ 推荐查看天气:https://www.0dtq.com/hongya/zuotian.html 推荐查看天气:https://www.0dtq.com/hongya/7tian.html 推荐查看天气:https://www.0dtq.com/hongya/10tian.html 推荐查看天气:https://www.0dtq.com/hongya/15tian.html 推荐查看天气:https://www.0dtq.com/hongya/40tian.html 推荐查看天气:https://www.0dtq.com/danling/ 推荐查看天气:https://www.0dtq.com/danling/zuotian.html 推荐查看天气:https://www.0dtq.com/danling/7tian.html 推荐查看天气:https://www.0dtq.com/danling/10tian.html 推荐查看天气:https://www.0dtq.com/danling/15tian.html 推荐查看天气:https://www.0dtq.com/danling/40tian.html 推荐查看天气:https://www.0dtq.com/qingshen/ 推荐查看天气:https://www.0dtq.com/qingshen/zuotian.html 推荐查看天气:https://www.0dtq.com/qingshen/7tian.html 推荐查看天气:https://www.0dtq.com/qingshen/10tian.html 推荐查看天气:https://www.0dtq.com/qingshen/15tian.html 推荐查看天气:https://www.0dtq.com/qingshen/40tian.html 推荐查看天气:https://www.0dtq.com/yibin/ 推荐查看天气:https://www.0dtq.com/yibin/zuotian.html 推荐查看天气:https://www.0dtq.com/yibin/7tian.html 推荐查看天气:https://www.0dtq.com/yibin/10tian.html 推荐查看天气:https://www.0dtq.com/yibin/15tian.html 推荐查看天气:https://www.0dtq.com/yibin/40tian.html 推荐查看天气:https://www.0dtq.com/cuiping/ 推荐查看天气:https://www.0dtq.com/cuiping/zuotian.html 推荐查看天气:https://www.0dtq.com/cuiping/7tian.html 推荐查看天气:https://www.0dtq.com/cuiping/10tian.html 推荐查看天气:https://www.0dtq.com/cuiping/15tian.html 推荐查看天气:https://www.0dtq.com/cuiping/40tian.html 推荐查看天气:https://www.0dtq.com/yibinxian/ 推荐查看天气:https://www.0dtq.com/yibinxian/zuotian.html 推荐查看天气:https://www.0dtq.com/yibinxian/7tian.html 推荐查看天气:https://www.0dtq.com/yibinxian/10tian.html 推荐查看天气:https://www.0dtq.com/yibinxian/15tian.html 推荐查看天气:https://www.0dtq.com/yibinxian/40tian.html 推荐查看天气:https://www.0dtq.com/nanxi/ 推荐查看天气:https://www.0dtq.com/nanxi/zuotian.html 推荐查看天气:https://www.0dtq.com/nanxi/7tian.html 推荐查看天气:https://www.0dtq.com/nanxi/10tian.html 推荐查看天气:https://www.0dtq.com/nanxi/15tian.html 推荐查看天气:https://www.0dtq.com/nanxi/40tian.html 推荐查看天气:https://www.0dtq.com/jiangan/ 推荐查看天气:https://www.0dtq.com/jiangan/zuotian.html 推荐查看天气:https://www.0dtq.com/jiangan/7tian.html 推荐查看天气:https://www.0dtq.com/jiangan/10tian.html 推荐查看天气:https://www.0dtq.com/jiangan/15tian.html 推荐查看天气:https://www.0dtq.com/jiangan/40tian.html 推荐查看天气:https://www.0dtq.com/changningxian/ 推荐查看天气:https://www.0dtq.com/changningxian/zuotian.html 推荐查看天气:https://www.0dtq.com/changningxian/7tian.html 推荐查看天气:https://www.0dtq.com/changningxian/10tian.html 推荐查看天气:https://www.0dtq.com/changningxian/15tian.html 推荐查看天气:https://www.0dtq.com/changningxian/40tian.html 推荐查看天气:https://www.0dtq.com/gaoxian/ 推荐查看天气:https://www.0dtq.com/gaoxian/zuotian.html 推荐查看天气:https://www.0dtq.com/gaoxian/7tian.html 推荐查看天气:https://www.0dtq.com/gaoxian/10tian.html 推荐查看天气:https://www.0dtq.com/gaoxian/15tian.html 推荐查看天气:https://www.0dtq.com/gaoxian/40tian.html 推荐查看天气:https://www.0dtq.com/gongxian/ 推荐查看天气:https://www.0dtq.com/gongxian/zuotian.html 推荐查看天气:https://www.0dtq.com/gongxian/7tian.html 推荐查看天气:https://www.0dtq.com/gongxian/10tian.html 推荐查看天气:https://www.0dtq.com/gongxian/15tian.html 推荐查看天气:https://www.0dtq.com/gongxian/40tian.html 推荐查看天气:https://www.0dtq.com/junlian/ 推荐查看天气:https://www.0dtq.com/junlian/zuotian.html 推荐查看天气:https://www.0dtq.com/junlian/7tian.html 推荐查看天气:https://www.0dtq.com/junlian/10tian.html 推荐查看天气:https://www.0dtq.com/junlian/15tian.html 推荐查看天气:https://www.0dtq.com/junlian/40tian.html 推荐查看天气:https://www.0dtq.com/xingwen/ 推荐查看天气:https://www.0dtq.com/xingwen/zuotian.html 推荐查看天气:https://www.0dtq.com/xingwen/7tian.html 推荐查看天气:https://www.0dtq.com/xingwen/10tian.html 推荐查看天气:https://www.0dtq.com/xingwen/15tian.html 推荐查看天气:https://www.0dtq.com/xingwen/40tian.html 推荐查看天气:https://www.0dtq.com/pingshan/ 推荐查看天气:https://www.0dtq.com/pingshan/zuotian.html 推荐查看天气:https://www.0dtq.com/pingshan/7tian.html 推荐查看天气:https://www.0dtq.com/pingshan/10tian.html 推荐查看天气:https://www.0dtq.com/pingshan/15tian.html 推荐查看天气:https://www.0dtq.com/pingshan/40tian.html 推荐查看天气:https://www.0dtq.com/guangan/ 推荐查看天气:https://www.0dtq.com/guangan/zuotian.html 推荐查看天气:https://www.0dtq.com/guangan/7tian.html 推荐查看天气:https://www.0dtq.com/guangan/10tian.html 推荐查看天气:https://www.0dtq.com/guangan/15tian.html 推荐查看天气:https://www.0dtq.com/guangan/40tian.html 推荐查看天气:https://www.0dtq.com/yuechi/ 推荐查看天气:https://www.0dtq.com/yuechi/zuotian.html 推荐查看天气:https://www.0dtq.com/yuechi/7tian.html 推荐查看天气:https://www.0dtq.com/yuechi/10tian.html 推荐查看天气:https://www.0dtq.com/yuechi/15tian.html 推荐查看天气:https://www.0dtq.com/yuechi/40tian.html 推荐查看天气:https://www.0dtq.com/wusheng/ 推荐查看天气:https://www.0dtq.com/wusheng/zuotian.html 推荐查看天气:https://www.0dtq.com/wusheng/7tian.html 推荐查看天气:https://www.0dtq.com/wusheng/10tian.html 推荐查看天气:https://www.0dtq.com/wusheng/15tian.html 推荐查看天气:https://www.0dtq.com/wusheng/40tian.html 推荐查看天气:https://www.0dtq.com/linshui/ 推荐查看天气:https://www.0dtq.com/linshui/zuotian.html 推荐查看天气:https://www.0dtq.com/linshui/7tian.html 推荐查看天气:https://www.0dtq.com/linshui/10tian.html 推荐查看天气:https://www.0dtq.com/linshui/15tian.html 推荐查看天气:https://www.0dtq.com/linshui/40tian.html 推荐查看天气:https://www.0dtq.com/guanganhuaning/ 推荐查看天气:https://www.0dtq.com/guanganhuaning/zuotian.html 推荐查看天气:https://www.0dtq.com/guanganhuaning/7tian.html 推荐查看天气:https://www.0dtq.com/guanganhuaning/10tian.html 推荐查看天气:https://www.0dtq.com/guanganhuaning/15tian.html 推荐查看天气:https://www.0dtq.com/guanganhuaning/40tian.html 推荐查看天气:https://www.0dtq.com/dazhou/ 推荐查看天气:https://www.0dtq.com/dazhou/zuotian.html 推荐查看天气:https://www.0dtq.com/dazhou/7tian.html 推荐查看天气:https://www.0dtq.com/dazhou/10tian.html 推荐查看天气:https://www.0dtq.com/dazhou/15tian.html 推荐查看天气:https://www.0dtq.com/dazhou/40tian.html 推荐查看天气:https://www.0dtq.com/daxian/ 推荐查看天气:https://www.0dtq.com/daxian/zuotian.html 推荐查看天气:https://www.0dtq.com/daxian/7tian.html 推荐查看天气:https://www.0dtq.com/daxian/10tian.html 推荐查看天气:https://www.0dtq.com/daxian/15tian.html 推荐查看天气:https://www.0dtq.com/daxian/40tian.html 推荐查看天气:https://www.0dtq.com/xuanhan/ 推荐查看天气:https://www.0dtq.com/xuanhan/zuotian.html 推荐查看天气:https://www.0dtq.com/xuanhan/7tian.html 推荐查看天气:https://www.0dtq.com/xuanhan/10tian.html 推荐查看天气:https://www.0dtq.com/xuanhan/15tian.html 推荐查看天气:https://www.0dtq.com/xuanhan/40tian.html 推荐查看天气:https://www.0dtq.com/kaijiang/ 推荐查看天气:https://www.0dtq.com/kaijiang/zuotian.html 推荐查看天气:https://www.0dtq.com/kaijiang/7tian.html 推荐查看天气:https://www.0dtq.com/kaijiang/10tian.html 推荐查看天气:https://www.0dtq.com/kaijiang/15tian.html 推荐查看天气:https://www.0dtq.com/kaijiang/40tian.html 推荐查看天气:https://www.0dtq.com/dazhu/ 推荐查看天气:https://www.0dtq.com/dazhu/zuotian.html 推荐查看天气:https://www.0dtq.com/dazhu/7tian.html 推荐查看天气:https://www.0dtq.com/dazhu/10tian.html 推荐查看天气:https://www.0dtq.com/dazhu/15tian.html 推荐查看天气:https://www.0dtq.com/dazhu/40tian.html 推荐查看天气:https://www.0dtq.com/quxian/ 推荐查看天气:https://www.0dtq.com/quxian/zuotian.html 推荐查看天气:https://www.0dtq.com/quxian/7tian.html 推荐查看天气:https://www.0dtq.com/quxian/10tian.html 推荐查看天气:https://www.0dtq.com/quxian/15tian.html 推荐查看天气:https://www.0dtq.com/quxian/40tian.html 推荐查看天气:https://www.0dtq.com/wanyuan/ 推荐查看天气:https://www.0dtq.com/wanyuan/zuotian.html 推荐查看天气:https://www.0dtq.com/wanyuan/7tian.html 推荐查看天气:https://www.0dtq.com/wanyuan/10tian.html 推荐查看天气:https://www.0dtq.com/wanyuan/15tian.html 推荐查看天气:https://www.0dtq.com/wanyuan/40tian.html 推荐查看天气:https://www.0dtq.com/yaan/ 推荐查看天气:https://www.0dtq.com/yaan/zuotian.html 推荐查看天气:https://www.0dtq.com/yaan/7tian.html 推荐查看天气:https://www.0dtq.com/yaan/10tian.html 推荐查看天气:https://www.0dtq.com/yaan/15tian.html 推荐查看天气:https://www.0dtq.com/yaan/40tian.html 推荐查看天气:https://www.0dtq.com/mingshan/ 推荐查看天气:https://www.0dtq.com/mingshan/zuotian.html 推荐查看天气:https://www.0dtq.com/mingshan/7tian.html 推荐查看天气:https://www.0dtq.com/mingshan/10tian.html 推荐查看天气:https://www.0dtq.com/mingshan/15tian.html