A
A
Artur Aralin2019-12-27 21:59:20
Node.js
Artur Aralin, 2019-12-27 21:59:20

Is it possible to use one MessagePort for many workers?

I have a worker A that is created and sends a MessagePort in response

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

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

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

parentPort.postMessage(port2, [port2]);

Walker code that will send data to the port
// sub_worker.js
const { parentPort, MessageChannel } = require('worker_threads');

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

In this case, it gives an error DataCloneError: MessagePort in transfer list is already detached
// 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]);
  }
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lev Zabudkin, 2019-12-28
@zabudkin

detail and everything will be

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question