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)?

2 Answers 2

4

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]
);
Sign up to request clarification or add additional context in comments.

Comments

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/

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.