0

So, here is what I am trying to achieve:

  1. Call a specific function onMessage() in main thread from web-worker.
  2. Passing an array of transferable objects i.e. Uint16Array buffer, Float32Array buffer etc.
  3. Along with all of above, I want to pass a simple boolean object or an integer or a string value while posting message.

For example:

const cornersArray = new Uint16Array(5000), // should go as Transferable object
  trailsArray = new Float32Array(7000); // should go as Transferable object

const state = 1, // integer
  quality = 'High', // string
  isTracking = true; // boolean


this.Worker.postMessage({
  event: 'ShowTrails',
  data: {
    cornersArray: cornersArray,
    trailsArray: trailsArray,
    state: state,
    quality: quality,
    isTracking: isTracking
  }
}, [cornersArray.buffer, trailsArray.buffer]);

So, onMessage() at main thread, this should call ShowTrails() and data should be passed as a parameter. But this is throwing error that objects passed are not detachable, failing in postMessage().

I am very noob in this, first time using web workers, please help me how to make this happen. I must be doing something wrong here while passing data.

Thanks!

aman
  • 47
  • 5
  • you could send the data that the data has in object form, eg `( [{type:"buffer",data}] )` and have the worker re-create the buffer based on the information given – The Bomb Squad May 25 '22 at 17:00
  • 1
    This code should work just fine: https://jsfiddle.net/g9x4fhp8/ Either you are doing something else than what's shown here, either your `Uint16Array` or `Float32Array` aren't the original constructors. – Kaiido May 26 '22 at 05:15
  • @Kaiido Yeah, you are right, it is working. There was some issue from my side while passing data. Thanks! – aman Jun 02 '22 at 17:46

1 Answers1

-1

You are not passing the transferrable buffer correctly. Try this:

this.Worker.postMessage({
  event: 'ShowTrails',
  data: {
    cornersArray: cornersArray.buffer,
    trailsArray: trailsArray.buffer,
    state: state,
    quality: quality,
    isTracking: isTracking
  }
}, [cornersArray.buffer, trailsArray.buffer]);
rayen
  • 190
  • 3
  • 12
  • 1
    You need to pass the ArrayBuffer only in the *transferrables* list, in the body of the postMessage data you can keep the TypedArrays just fine. What OP does should work. – Kaiido May 26 '22 at 05:17