https://developer.mozilla.org/zh-CN/docs/Web/API/MessageChannel
node中使用
const {MessageChannel} = require('worker_threads')
const channel = new MessageChannel();
const port1 = channel.port1;
const port2 = channel.port2;
port1.onmessage = function (event) {
console.log("port1收到来自port2的数据:" + event.data);
}
port2.onmessage = function (event) {
console.log("port2收到来自port1的数据:" + event.data);
}
port1.postMessage("发送给port2");
port2.postMessage("发送给port1");
// port2收到来自port1的数据:发送给port2
// port1收到来自port2的数据:发送给port1
https://developer.mozilla.org/zh-CN/docs/Web/API/Worker/postMessage
worker中postMessage的第一个参数会被深拷贝, 但是port不能拷贝, 所以需要用第二个参数传进去
语法
myWorker.postMessage(aMessage, transferList);
参数
aMessage
The object to deliver to the worker; this will be in the data field in the event delivered to the DedicatedWorkerGlobalScope.onmessage
handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
transferList 可选
一个可选的 Transferable
对象的数组,用于传递所有权。如果一个对象的所有权被转移,在发送它的上下文中将变为不可用(中止),并且只有在它被发送到的 worker 中可用。
可转移对象是如 ArrayBuffer
,MessagePort
或 ImageBitmap
的实例对象。transferList 数组中不可传入 null。
Returns
main
在浏览器中使用不需要require
const w1 = new Worker("./w1.js");
const w2 = new Worker("./w2.js");
const ch = new MessageChannel();
w1.postMessage(
'port1', [ch.port1]
);
w2.postMessage("port2", [ch.port2]);
w2.onmessage = function (e) {
console.log('main w2 receive ' + e.data);
}
w1
self.addEventListener('message', e => {
console.log('data', e)
const port = e.ports[0];
port.postMessage(e.data + " this is from worker1")
})
w2
self.addEventListener('message', function (e) {
const port = e.ports[0];
port.onmessage = function (e) {
postMessage('w2 receive ' + e.data)
}
})
数据流向为
main -> w1 -> port1 -> port2 -> main
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/3188953