1

yanni's answer shows how to send (transfer ownership) one buffer to a web worker: Using transferable objects from a Web Worker

How would I send multiple buffers (in an array) to a web worker (without copying)?

Community
  • 1
  • 1
Agamemnus
  • 1,395
  • 4
  • 17
  • 41

2 Answers2

3

This has been answered elsewhere, but google brought me here first before I eventually found the answer here.

You can pass multiple buffers to a web worker without performing a copy using Transferable objects:

The worker case, the first argument is the data and the second is the list of items that should be transferred. The first argument doesn't have to be an ArrayBuffer by the way. For example, it can be a JSON object:

worker.postMessage(
  {data: int8View, moreData: anotherBuffer},
  [int8View.buffer, anotherBuffer]
);
Corey Cole
  • 2,262
  • 1
  • 26
  • 43
2

Worker#postMessage takes an array of transferable objects,

var worker = new Worker("...");
var buffers = [new ArrayBuffer, new ArrayBuffer, new ArrayBuffer];
var message = {buffers: buffers};

worker.postMessage(message, buffers);

Here's an example fiddle, http://jsfiddle.net/g247v/

tantalor
  • 119
  • 6
  • Thanks, but: (1): that's not an array, that's an array wrapped in an object with a 'buffers' property (all that is documented on MDN is [arrayBuffer], not {buffers: [arrayBuffer]}) -- assuming that works, that is a great find. (2) the fiddle doesn't work.. alerts and console.log aren't defined in web workers. – Agamemnus Feb 28 '14 at 22:12
  • 1
    The key is the second argument to postMessage, which takes the array of transferable objects that you are looking for. This is where you put the buffers you want to transfer. The first argument is just an arbitrary message object. – tantalor Mar 07 '14 at 23:24