- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:module
API - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
Node.js v18.12.1 documentation
- Node.js v18.12.1
-
► Table of contents
- Worker threads
worker.getEnvironmentData(key)
worker.isMainThread
worker.markAsUntransferable(object)
worker.moveMessagePortToContext(port, contextifiedSandbox)
worker.parentPort
worker.receiveMessageOnPort(port)
worker.resourceLimits
worker.SHARE_ENV
worker.setEnvironmentData(key[, value])
worker.threadId
worker.workerData
- Class:
BroadcastChannel extends EventTarget
- Class:
MessageChannel
- Class:
MessagePort
- Class:
Worker
new Worker(filename[, options])
- Event:
'error'
- Event:
'exit'
- Event:
'message'
- Event:
'messageerror'
- Event:
'online'
worker.getHeapSnapshot()
worker.performance
worker.postMessage(value[, transferList])
worker.ref()
worker.resourceLimits
worker.stderr
worker.stdin
worker.stdout
worker.terminate()
worker.threadId
worker.unref()
- Notes
- Worker threads
-
► Index
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:module
API - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- ► Other versions
- ► Options
Table of contents
- Worker threads
worker.getEnvironmentData(key)
worker.isMainThread
worker.markAsUntransferable(object)
worker.moveMessagePortToContext(port, contextifiedSandbox)
worker.parentPort
worker.receiveMessageOnPort(port)
worker.resourceLimits
worker.SHARE_ENV
worker.setEnvironmentData(key[, value])
worker.threadId
worker.workerData
- Class:
BroadcastChannel extends EventTarget
- Class:
MessageChannel
- Class:
MessagePort
- Class:
Worker
new Worker(filename[, options])
- Event:
'error'
- Event:
'exit'
- Event:
'message'
- Event:
'messageerror'
- Event:
'online'
worker.getHeapSnapshot()
worker.performance
worker.postMessage(value[, transferList])
worker.ref()
worker.resourceLimits
worker.stderr
worker.stdin
worker.stdout
worker.terminate()
worker.threadId
worker.unref()
- Notes
Worker threads#
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_process
或cluster
不同,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线程选项,特别是argv
和execArgv
选项。