如何在 Node.js 中的两个工作线程之间创建直接通信通道

How do I create a direct communication channel between two worker threads in Node.js

有没有办法在两个工作线程之间使用 new MessageChannel 创建直接通信通道?例如:我使用 worker_thread API 创建了一个主线程 P,它创建了两个工作线程 W1W2

P -> W1
  -> W2

我想直接启用 W1W2 之间的通信,而不是使用 parentPort 通过 P

使用new MessageChannel()生成双向通信通道。

index.js

const { Worker } = require('worker_threads');

const path = require('path'); 

const w1 = new Worker(path.join(__dirname,'./worker1.js'));
const w2 = new Worker(path.join(__dirname,'./worker2.js'));

w1.once('message', value => {
    w2.postMessage({
        port: value.port
    }, [value.port]);
});

w2.once('message', value => {
    w1.postMessage({
        port: value.port
    }, [value.port]);
});

worker1.js

const { MessageChannel, parentPort,  } = require('worker_threads');

let woker2Port;
console.log('worker1 started');

const { port1, port2 } = new MessageChannel();
port1.on('message', (value) => {
    console.log(value);
});

parentPort.postMessage({
    port: port2,
}, [port2]);

parentPort.on('message', value => {
    if (value.port) {
        woker2Port = value.port;
        woker2Port.postMessage({msg:'i am worker1!'});// send msg to worker2
        return;
    }
});

worker2.js

const { MessageChannel, parentPort,  } = require('worker_threads');

let woker1Port;
console.log('worker2 started');

const { port1, port2 } = new MessageChannel();
port1.on('message', (value) => {
    console.log(value);
});

parentPort.postMessage({
    port: port2,
}, [port2]);

parentPort.on('message', value => {
    if (value.port) {
        woker1Port = value.port;
        woker1Port.postMessage({msg:'i am worker2!'});// send msg to worker1
    }
});

注意:如果您在 VSCode 中调试此代码,您将不会在 worker1.jsworker2.js 中看到日志打印。 运行 node index 直接或在 ndb 中调试都可以!