const {Worker, isMainThread, parentPort, MessageChannel } = require('node:worker_threads');
if(isMainThread)
{
let worker1 = new Worker(__filename,{argv:['worker1']})
let worker2 = new Worker(__filename,{argv:['worker2']})
const {port1, port2} = new MessageChannel
worker1.postMessage({port:port1},[port1])
worker2.postMessage({port:port2},[port2])
}
else
{
//use process.argv to differentiate between worker1 and worker2
let workerName = process.argv[2]
parentPort.once('message',value=>{
let myport = value.port
myport.on('message',(data)=>{
console.log(`${workerName} got:${data}`)
//every time the data was increacsed by 1
setTimeout(()=>{myport.postMessage(data+1)},1000)
})
if(workerName === 'worker1')
{
//let worker1 to send the intial message
myport.postMessage(1)
}
})
}
2条答案
按热度按时间nzrxty8p1#
使用
new MessageChannel()
生成双向通信通道。index.js
worker1.js
worker2.js
注意:如果你在VSCode中调试这段代码,你不会在
worker1.js
和worker2.js
中看到日志打印。直接运行node index
或者在ndb中调试它都可以!hrysbysz2#
"也许你可以试试这个“