[英]WebWorker - Transferring an array which contains objects
I have an array which I need to transfer from a WebWorker back to the main thread. 我有一个数组,需要将其从WebWorker传输回主线程。 As far as I know, only ArrayBuffers and TypedArrays are transferable and anything else is copied instead of transferred.
据我所知,只有ArrayBuffers和TypedArrays是可转让的,其他任何东西都是复制而不是转让。
Problem I'm having is the array contains objects, so I'm not sure how to transfer them (which is needed due to the huge size). 我遇到的问题是数组包含对象,所以我不确定如何传输它们(由于尺寸巨大而需要)。
For example assume I have: 例如,假设我有:
function something() {
this.x = 1;
this.y = 2;
this.z = 3;
}
var array = [];
for (var x = 0; x < 6; x++) {
array[x] = new something();
}
Is there a way I can convert the array to an ArrayBuffer, transfer it then convert it back? 有没有一种方法可以将数组转换为ArrayBuffer,进行传输然后再转换回?
Thanks for the help! 谢谢您的帮助!
Consider posting for each element of the array (object?) when the object is created. 创建对象时,请考虑为数组的每个元素(object?)发布。 Then put it in an array in the onmessage handler.
然后将其放在onmessage处理程序中的数组中。
function something() {
this.x = 1;
this.y = 2;
this.z = 3;
}
var array = [];
for (var x = 0; x < 6; x++) {
postMessage(new something());
}
This should work for simple objects, like the one in the sample but you will have to test the boundaries. 这应该适用于简单的对象,例如示例中的对象,但是您必须测试边界。
Data passed between the main page and workers are copied, not shared.
主页和工作人员之间传递的数据将被复制,而不是共享。 Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end.
对象在交给工作人员时会先序列化,然后在另一端反序列化。 The page and worker do not share the same instance, so the end result is that a duplicate is created on each end.
页和工作器不共享同一实例,因此最终结果是在每个端均创建了一个副本。 Most browsers implement this feature as structured cloning.
大多数浏览器将此功能实现为结构化克隆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.