类:BroadcastChannel extends EventTarget
¥Class: BroadcastChannel extends EventTarget
BroadcastChannel 的实例允许与绑定到相同通道名称的所有其他 BroadcastChannel 实例进行异步的一对多通信。
¥Instances of BroadcastChannel allow asynchronous one-to-many communication
with all other BroadcastChannel instances bound to the same channel name.
import {
  isMainThread,
  BroadcastChannel,
  Worker,
} from 'node: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(new URL(import.meta.url));
} else {
  bc.postMessage('hello from every worker');
  bc.close();
}'use strict';
const {
  isMainThread,
  BroadcastChannel,
  Worker,
} = require('node: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();
}