我有一个工作人员创建 MessageChannel 并将其中一个端口发送到主线程
// worker1.js
const { parentPort, MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
console.log(msg);
})
parentPort.postMessage(port2, [port2]);
第二种类型的工作人员只是接收 MessagePort 并将数据发送到端口
// 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]);
}
})
当我将一个频道发送给多个工作人员时,问题是错误的。
错误文字:DataCloneError: MessagePort in transfer list is already detached