Using Transferable Objects From A Web Worker
Solution 1:
The answer given by sbr works, but it would cause a copy of the data to be made before being sent to the worker. That could be slow for a large amount of data. To use "transferable objects" you actually transfer the ownership of the object to or from the web worker. It's like passing by reference where a copy isn't made. The difference between it and the normal pass-by-reference is that the side that transferred the data can no longer access it. I believe the way you should send the data in your example is:
w.postMessage(r,[r]); // first arg is r, not 0 as in the question
And the way you would access it in the web worker:
addEventListener('message', function(event) {
var r = event.data;
});
In my own application I needed to send a large typed Float64Array from the web worker to the main thread, without the performance penalty of the copy. It took lots of trial and error and searching, so I figured I should include that example here for anyone else who gets stuck with a similar problem. This is the code that worked on the worker side (arr is my Float64Array):
self.postMessage(arr.buffer, [arr.buffer]);
On the receiving main thread I have:
theWorker.addEventListener('message', function(ev) {
var arr = newFloat64Array(ev.data); // just cast it to the desired type - no copy made// ...
});
Note that this works in Chrome, but maybe not most other browsers as of this date (haven't tried yet.) Also, if you want to send other information in addition to the large array, you can do this:
self.postMessage({foo:"foo", bar:arr.buffer}, [arr.buffer]);
On the receiving (in this example the main) thread:
theWorker.addEventListener('message', function(event) {
var foo = event.data.foo;
var arr = new Float64Array(event.data.bar); // cast it to the desired type// ...
});
Solution 2:
PostMesage(aMessage, transferList)
In transferList
you must specify transferable objects, which contained in aMessage
:
var objData =
{
str: "string",
ab: newArrayBuffer(100),
i8: newInt8Array(200)
};
objWorker.postMessage(objData, [objData.ab, objData.i8.buffer]);
On other side:
self.onmessage = function(objEvent)
{
var strText = objEvent.data.str;
var objTypedArray = objEvent.data.ab;
var objTypedArrayView = objEvent.data.i8;
}
Solution 3:
Try w.postMessage([0,r]). To use transferable objects, one needs to pass the array buffer as the second item on an array. See this
Solution 4:
this works for me :
//in the Main
var x = newArrayBuffer(1048576*128);
w.postMessage({buffer: x});
// In the worker thread, in message handler,
processMessage: function(ev){
var buffer = ev.data.buffer,
// other stuff . buffer is referenced correctly here.
}
Post a Comment for "Using Transferable Objects From A Web Worker"