4
4
5
5
> Stability: 1 - Experimental
6
6
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:
9
9
10
10
``` js
11
11
const worker = require (' worker_threads' );
@@ -58,6 +58,18 @@ added: v10.5.0
58
58
59
59
Is ` true ` if this code is not running inside of a [ ` Worker ` ] [ ] thread.
60
60
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
+
61
73
## worker.parentPort
62
74
<!-- YAML
63
75
added: v10.5.0
@@ -72,6 +84,23 @@ using `worker.on('message')`, and messages sent from the parent thread
72
84
using ` worker.postMessage() ` will be available in this thread using
73
85
` parentPort.on('message') ` .
74
86
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
+
75
104
## worker.threadId
76
105
<!-- YAML
77
106
added: v10.5.0
@@ -91,6 +120,19 @@ added: v10.5.0
91
120
An arbitrary JavaScript value that contains a clone of the data passed
92
121
to this thread’s ` Worker ` constructor.
93
122
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
+
94
136
## Class: MessageChannel
95
137
<!-- YAML
96
138
added: v10.5.0
@@ -134,6 +176,20 @@ added: v10.5.0
134
176
The ` 'close' ` event is emitted once either side of the channel has been
135
177
disconnected.
136
178
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
+
137
193
### Event: 'message'
138
194
<!-- YAML
139
195
added: v10.5.0
@@ -156,6 +212,9 @@ Disables further sending of messages on either side of the connection.
156
212
This method can be called when no further communication will happen over this
157
213
` MessagePort ` .
158
214
215
+ The [ ` 'close' ` event] [ ] will be emitted on both ` MessagePort ` instances that
216
+ are part of the channel.
217
+
159
218
### port.postMessage(value[ , transferList] )
160
219
<!-- YAML
161
220
added: v10.5.0
@@ -166,9 +225,28 @@ added: v10.5.0
166
225
167
226
Sends a JavaScript value to the receiving side of this channel.
168
227
` 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
+ ```
172
250
173
251
` transferList ` may be a list of ` ArrayBuffer ` and ` MessagePort ` objects.
174
252
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`.
182
260
` value ` may still contain ` ArrayBuffer ` instances that are not in
183
261
` transferList ` ; in that case, the underlying memory is copied rather than moved.
184
262
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
+
185
287
Because the object cloning uses the structured clone algorithm,
186
288
non-enumerable properties, property accessors, and object prototypes are
187
289
not preserved. In particular, [ ` Buffer ` ] [ ] objects will be read as
@@ -215,6 +317,9 @@ Starts receiving messages on this `MessagePort`. When using this port
215
317
as an event emitter, this will be called automatically once ` 'message' `
216
318
listeners are attached.
217
319
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
+
218
323
### port.unref()
219
324
<!-- YAML
220
325
added: v10.5.0
@@ -465,12 +570,14 @@ Calling `unref()` on a worker will allow the thread to exit if this is the only
465
570
active handle in the event system. If the worker is already ` unref() ` ed calling
466
571
` unref() ` again will have no effect.
467
572
573
+ [ `'close'` event ] : #worker_threads_event_close
468
574
[ `Buffer` ] : buffer.html
469
575
[ `EventEmitter` ] : events.html
470
576
[ `EventTarget` ] : https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
471
577
[ `MessagePort` ] : #worker_threads_class_messageport
472
578
[ `SharedArrayBuffer` ] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
473
579
[ `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
474
581
[ `Worker` ] : #worker_threads_class_worker
475
582
[ `cluster` module ] : cluster.html
476
583
[ `inspector` ] : inspector.html
0 commit comments