Answer the question
In order to leave comments, you need to log in
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]);
// sub_worker.js
const { parentPort, MessageChannel } = require('worker_threads');
parentPort.on('message', (port) => {
port.postMessage('some data')
});
// 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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question