Search code examples
javascriptweb-workertransferable

Using transferable objects from a Web Worker


I currently have this code to create a Web Worker:

w = new Worker("webwork.js");
w.onmessage = function(event) { alert(event.data); }

And then the webwork.js code for the Web Worker:

self.onmessage = function(event) {
    //var ss=r;  //Causes error because of undefined
    var ss="";
    for(var currProp in event) {
        ss+=("event."+currProp+"="+event[currProp]+"\n");
    }
    postMessage(ss);
}

Now I want to transfer a 128-Megabyte ArrayBuffer with this code:

var r = new ArrayBuffer(1048576*128);
w.postMessage(0, [r]);

Now that I have supposedly transferred the variable r, how do I access it from the Web Worker itself. I have tried event.r, just r, self.r and other things like trying to add a second function argument for the array of ArrayBuffers, but nothing works.

How can I access the transferred variable(s) from the Web Worker?


Solution

  • postMesage(aMessage, transferList)
    

    In transferList, you must specify the transferable objects that are contained in aMessage:

    const objData = {
        strText: "coolcmd",
        objArrayBuffer: new ArrayBuffer(10),
        objTypedArray: new Int8Array(20)
    };
    objWorker.postMessage(
        objData,
        [objData.objArrayBuffer, objData.objTypedArray.buffer]
    );
    // The transferred objects are now empty (detached
    // from resource). Specifically,
    // objData.objArrayBuffer.byteLength returns 0, and
    // any access to its content will throw an exception.
    

    In the worker:

    self.onmessage = objEvent => {
        console.log(
            objEvent.data.strText,
            objEvent.data.objArrayBuffer,
            objEvent.data.objTypedArray
        );
    };
    

    Or using an object destructuring:

    self.onmessage = ({data: {strText, objArrayBuffer, objTypedArray}}) => {
        console.log(
            strText,
            objArrayBuffer,
            objTypedArray
        );
    };
    

    List of transferable objects.