From 802d44b1a9cf61ee05638ca22eaa850de27db398 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 26 Nov 2020 13:54:23 -0800 Subject: [PATCH] worker: add experimental BroadcastChannel Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/36271 Reviewed-By: Anna Henningsen Reviewed-By: Benjamin Gruenbaum --- doc/api/worker_threads.md | 92 ++++++++ lib/internal/worker/io.js | 87 ++++++- lib/worker_threads.js | 2 + src/node_messaging.cc | 217 +++++++++++++----- src/node_messaging.h | 76 +++++- .../test-worker-broadcastchannel-wpt.js | 148 ++++++++++++ test/parallel/test-worker-broadcastchannel.js | 135 +++++++++++ tools/doc/type-parser.js | 4 + 8 files changed, 689 insertions(+), 72 deletions(-) create mode 100644 test/parallel/test-worker-broadcastchannel-wpt.js create mode 100644 test/parallel/test-worker-broadcastchannel.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index bfc754b77cad19..8c4c5b3854fb4d 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -274,6 +274,98 @@ if (isMainThread) { } ``` +## Class: `BroadcastChannel extends EventTarget` + + +> Stability: 1 - Experimental + +Instances of `BroadcastChannel` allow asynchronous one-to-many communication +with all other `BroadcastChannel` instances bound to the same channel name. + +```js +'use strict'; + +const { + isMainThread, + BroadcastChannel, + Worker +} = require('worker_threads'); + +const bc = new BroadcastChannel('hello'); + +if (isMainThread) { + let c = 0; + bc.onmessage = (event) => { + console.log(event.data); + if (++c === 10) bc.close(); + }; + for (let n = 0; n < 10; n++) + new Worker(__filename); +} else { + bc.postMessage('hello from every worker'); + bc.close(); +} +``` + +### `new BroadcastChannel(name)` + + +* `name` {any} The name of the channel to connect to. Any JavaScript value + that can be converted to a string using ``${name}`` is permitted. + +### `broadcastChannel.close()` + + +Closes the `BroadcastChannel` connection. + +### `broadcastChannel.onmessage` + + +* Type: {Function} Invoked with a single `MessageEvent` argument + when a message is received. + +### `broadcastChannel.onmessageerror` + + +* Type: {Function} Invoked with a received message cannot be + deserialized. + +### `broadcastChannel.postMessage(message)` + + +* `message` {any} Any cloneable JavaScript value. + +### `broadcastChannel.ref()` + + +Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed +BroadcastChannel will *not* let the program exit if it's the only active handle +left (the default behavior). If the port is `ref()`ed, calling `ref()` again +will have no effect. + +### `broadcastChannel.unref()` + + +Calling `unref()` on a BroadcastChannel will allow the thread to exit if this +is the only active handle in the event system. If the BroadcastChannel is +already `unref()`ed calling `unref()` again will have no effect. + ## Class: `MessageChannel`