Skip to content

Commit a18b847

Browse files
addaleaxrvagg
authored andcommitted
doc: improve worker_threads documentation
This adds a few examples and clarifications. PR-URL: #26110 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Anto Aravinth <anto.aravinth.cse@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
1 parent d3525d7 commit a18b847

File tree

1 file changed

+112
-5
lines changed

1 file changed

+112
-5
lines changed

doc/api/worker_threads.md

+112-5
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
> Stability: 1 - Experimental
66
7-
The `worker_threads` module enables the use of threads with message channels
8-
between them. To access it:
7+
The `worker_threads` module enables the use of threads that execute JS code
8+
in parallel. To access it:
99

1010
```js
1111
const worker = require('worker_threads');
@@ -58,6 +58,18 @@ added: v10.5.0
5858

5959
Is `true` if this code is not running inside of a [`Worker`][] thread.
6060

61+
```js
62+
const { Worker, isMainThread } = require('worker_threads');
63+
64+
if (isMainThread) {
65+
// This re-loads the current file inside a Worker instance.
66+
new Worker(__filename);
67+
} else {
68+
console.log('Inside Worker!');
69+
console.log(isMainThread); // Prints 'false'.
70+
}
71+
```
72+
6173
## worker.parentPort
6274
<!-- YAML
6375
added: v10.5.0
@@ -72,6 +84,23 @@ using `worker.on('message')`, and messages sent from the parent thread
7284
using `worker.postMessage()` will be available in this thread using
7385
`parentPort.on('message')`.
7486

87+
```js
88+
const { Worker, isMainThread, parentPort } = require('worker_threads');
89+
90+
if (isMainThread) {
91+
const worker = new Worker(__filename);
92+
worker.once('message', (message) => {
93+
console.log(message); // Prints 'Hello, world!'.
94+
});
95+
worker.postMessage('Hello, world!');
96+
} else {
97+
// When a message from the parent thread is received, send it back:
98+
parentPort.once('message', (message) => {
99+
parentPort.postMessage(message);
100+
});
101+
}
102+
```
103+
75104
## worker.threadId
76105
<!-- YAML
77106
added: v10.5.0
@@ -91,6 +120,19 @@ added: v10.5.0
91120
An arbitrary JavaScript value that contains a clone of the data passed
92121
to this thread’s `Worker` constructor.
93122

123+
The data is cloned as if using [`postMessage()`][`port.postMessage()`],
124+
according to the [HTML structured clone algorithm][].
125+
126+
```js
127+
const { Worker, isMainThread, workerData } = require('worker_threads');
128+
129+
if (isMainThread) {
130+
const worker = new Worker(__filename, { workerData: 'Hello, world!' });
131+
} else {
132+
console.log(workerData); // Prints 'Hello, world!'.
133+
}
134+
```
135+
94136
## Class: MessageChannel
95137
<!-- YAML
96138
added: v10.5.0
@@ -134,6 +176,20 @@ added: v10.5.0
134176
The `'close'` event is emitted once either side of the channel has been
135177
disconnected.
136178

179+
```js
180+
const { MessageChannel } = require('worker_threads');
181+
const { port1, port2 } = new MessageChannel();
182+
183+
// Prints:
184+
// foobar
185+
// closed!
186+
port2.on('message', (message) => console.log(message));
187+
port2.on('close', () => console.log('closed!'));
188+
189+
port1.postMessage('foobar');
190+
port1.close();
191+
```
192+
137193
### Event: 'message'
138194
<!-- YAML
139195
added: v10.5.0
@@ -156,6 +212,9 @@ Disables further sending of messages on either side of the connection.
156212
This method can be called when no further communication will happen over this
157213
`MessagePort`.
158214

215+
The [`'close'` event][] will be emitted on both `MessagePort` instances that
216+
are part of the channel.
217+
159218
### port.postMessage(value[, transferList])
160219
<!-- YAML
161220
added: v10.5.0
@@ -166,9 +225,28 @@ added: v10.5.0
166225

167226
Sends a JavaScript value to the receiving side of this channel.
168227
`value` will be transferred in a way which is compatible with
169-
the [HTML structured clone algorithm][]. In particular, it may contain circular
170-
references and objects like typed arrays that the `JSON` API is not able
171-
to stringify.
228+
the [HTML structured clone algorithm][].
229+
230+
In particular, the significant differences to `JSON` are:
231+
- `value` may contain circular references.
232+
- `value` may contain instances of builtin JS types such as `RegExp`s,
233+
`BigInt`s, `Map`s, `Set`s, etc.
234+
- `value` may contained typed arrays, both using `ArrayBuffer`s
235+
and `SharedArrayBuffer`s.
236+
- `value` may contain [`WebAssembly.Module`][] instances.
237+
- `value` may not contain native (C++-backed) objects other than `MessagePort`s.
238+
239+
```js
240+
const { MessageChannel } = require('worker_threads');
241+
const { port1, port2 } = new MessageChannel();
242+
243+
port1.on('message', (message) => console.log(message));
244+
245+
const circularData = {};
246+
circularData.foo = circularData;
247+
// Prints: { foo: [Circular] }
248+
port2.postMessage(circularData);
249+
```
172250

173251
`transferList` may be a list of `ArrayBuffer` and `MessagePort` objects.
174252
After transferring, they will not be usable on the sending side of the channel
@@ -182,6 +260,30 @@ from either thread. They cannot be listed in `transferList`.
182260
`value` may still contain `ArrayBuffer` instances that are not in
183261
`transferList`; in that case, the underlying memory is copied rather than moved.
184262

263+
```js
264+
const { MessageChannel } = require('worker_threads');
265+
const { port1, port2 } = new MessageChannel();
266+
267+
port1.on('message', (message) => console.log(message));
268+
269+
const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
270+
// This posts a copy of `uint8Array`:
271+
port2.postMessage(uint8Array);
272+
// This does not copy data, but renders `uint8Array` unusable:
273+
port2.postMessage(uint8Array, [ uint8Array.buffer ]);
274+
275+
// The memory for the `sharedUint8Array` will be accessible from both the
276+
// original and the copy received by `.on('message')`:
277+
const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
278+
port2.postMessage(sharedUint8Array);
279+
280+
// This transfers a freshly created message port to the receiver.
281+
// This can be used, for example, to create communication channels between
282+
// multiple `Worker` threads that are children of the same parent thread.
283+
const otherChannel = new MessageChannel();
284+
port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
285+
```
286+
185287
Because the object cloning uses the structured clone algorithm,
186288
non-enumerable properties, property accessors, and object prototypes are
187289
not preserved. In particular, [`Buffer`][] objects will be read as
@@ -215,6 +317,9 @@ Starts receiving messages on this `MessagePort`. When using this port
215317
as an event emitter, this will be called automatically once `'message'`
216318
listeners are attached.
217319

320+
This method exists for parity with the Web `MessagePort` API. In Node.js,
321+
it is only useful for ignoring messages when no event listener is present.
322+
218323
### port.unref()
219324
<!-- YAML
220325
added: v10.5.0
@@ -465,12 +570,14 @@ Calling `unref()` on a worker will allow the thread to exit if this is the only
465570
active handle in the event system. If the worker is already `unref()`ed calling
466571
`unref()` again will have no effect.
467572

573+
[`'close'` event]: #worker_threads_event_close
468574
[`Buffer`]: buffer.html
469575
[`EventEmitter`]: events.html
470576
[`EventTarget`]: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
471577
[`MessagePort`]: #worker_threads_class_messageport
472578
[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
473579
[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
580+
[`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module
474581
[`Worker`]: #worker_threads_class_worker
475582
[`cluster` module]: cluster.html
476583
[`inspector`]: inspector.html

0 commit comments

Comments
 (0)