Node.js v18.12.1 documentation


Table of contents

Worker threads#

Stability: 2 - Stable

Source Code: lib/worker_threads.js

The node:worker_threads module enables the use of threads that execute JavaScript in parallel. node:worker_threads模块允许使用并行执行JavaScript的线程。To access it:要访问它:

const worker = require('node:worker_threads');

Workers (threads) are useful for performing CPU-intensive JavaScript operations. Worker(线程)对于执行CPU密集型JavaScript操作非常有用。They do not help much with I/O-intensive work. 它们对I/O密集型工作帮助不大。The Node.js built-in asynchronous I/O operations are more efficient than Workers can be.Node.js内置的异步I/O操作比Workers更高效。

Unlike child_process or cluster, worker_threads can share memory. child_processcluster不同,worker_threads可以共享内存。They do so by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.它们通过传输ArrayBuffer实例或共享SharedArrayBuffer实例来实现。

const {
Worker, isMainThread, parentPort, workerData
} = require('node:worker_threads');

if (isMainThread) {
module.exports = function parseJSAsync(script) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: script
});
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
};
} else {
const { parse } = require('some-js-parsing-library');
const script = workerData;
parentPort.postMessage(parse(script));
}

The above example spawns a Worker thread for each parseJSAsync() call. 上面的示例为每个parseJSAsync()调用生成一个Worker线程。In practice, use a pool of Workers for these kinds of tasks. 在实践中,为这些类型的任务使用Worker池。Otherwise, the overhead of creating Workers would likely exceed their benefit.否则,创建工人的开销可能会超过他们的收益。

When implementing a worker pool, use the AsyncResource API to inform diagnostic tools (e.g. to provide asynchronous stack traces) about the correlation between tasks and their outcomes. 在实现工作池时,使用AsyncResource API通知诊断工具(例如,提供异步堆栈跟踪)任务与其结果之间的相关性。See "Using AsyncResource for a Worker thread pool" in the async_hooks documentation for an example implementation.有关示例实现,请参阅async_hooks文档中的“将AsyncResource用于Worker线程池”

Worker threads inherit non-process-specific options by default. 默认情况下,工作线程继承非进程特定的选项。Refer to Worker constructor options to know how to customize worker thread options, specifically argv and execArgv options.请参阅Worker构造函数选项,了解如何自定义Worker线程选项,特别是argvexecArgv选项。