5

I have a worker which creates MessageChannel and sends one of ports to main thread

// worker1.js
const { parentPort, MessageChannel } = require('worker_threads');

const { port1, port2 } = new MessageChannel();

port1.on('message', (msg) => {
  console.log(msg);
})

parentPort.postMessage(port2, [port2]);

Second type of worker just receive MessagePort and send data into port

// sub_worker.js
const { parentPort, MessageChannel } = require('worker_threads');

parentPort.on('message',  (port) => {
  port.postMessage('some data')
});

Main thread code

// main thread
const { Worker } = require('worker_threads');

const mw = new Worker('worker1.js');
mw.on('message', (port) => {
  for (let i = 0; i < 5; i++) {
    const w = new Worker('sub_worker.js');
    w.postMessage(port, [port]);
  }
})

The problem is error when I send one channel to multiple workers.

Error text: DataCloneError: MessagePort in transfer list is already detached

2
  • Have you got the answer? I am also stuck with the same issue.
    – Mayur
    Jul 31, 2020 at 14:52
  • Also same problem
    – BierDav
    Nov 29, 2020 at 16:55

1 Answer 1

0

If anybody else is coming across this problem: it's not possible to do it the way you are trying. A channel is a one to one link between threads. So you've got two choices:

  1. Set up multiple channels, one per worker, and the main thread needs to post a message to each work individually
  2. Use a Broadcast channel. This is currently experimental.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.