8

I need to share an object between a client side application and a web worker and I heard about SharedArrayBuffers. This is what I'd like to do.

main.js

let myWorker = new Worker('/worker.js')
let mySab = new SharedArrayBuffer(1024)
let myObj = { foo: 'bar', bar: 'foo' }
// Save 'myObj' to 'mySab'
worker.postMessage(sab)

worker.js

self.onmessage = (e) => {
    let myObj = BLANK // Get 'myObj' from SharedArrayBuffer
}

Is this possible? The examples I've seen of ShareArrayBuffers only ever save numbers in the buffer. Any help is appreciated!

zlowe
  • 474
  • 4
  • 9
  • 1
    No. (`Shared`)`ArrayBuffer`s hold binary data, not objects. – Bergi Mar 16 '22 at 21:43
  • "*I need to share an object*" - what exactly do you mean by that? You can easily *send* the object to the web worker, who will receive a clone of the data. – Bergi Mar 16 '22 at 21:44
  • You would use a `SharedArrayBuffer` only when you really need multi-threaded access to shared memory. With all the problems that can cause. – Bergi Mar 16 '22 at 21:47
  • 1
    @Bergi Thanks, I know about sending it as a clone, just wondering if sharing was possible with an object or not. Makes sense that it only holds binary. – zlowe Mar 16 '22 at 21:57
  • No, it is not possible for objects to be shared. This would mean that object access would have to be implemented thread-safe, which it isn't. Share by communicating (through messages) between your workers, instead of attempting to communicate by sharing memory. – Bergi Mar 16 '22 at 22:01
  • 1
    There is [this project](https://github.com/GoogleChromeLabs/buffer-backed-object) you may want to have a look at. – Kaiido Mar 17 '22 at 14:48

1 Answers1

2

No, SharedArrayBuffers only store binary data. You can only send copies of objects via the built-in postMessage function.

Sources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

zlowe
  • 474
  • 4
  • 9
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 17 '22 at 06:56
  • 1
    can't you convert the Object to binary and vice-versa in the Worker? – João Pimentel Ferreira Sep 02 '22 at 21:49
  • I'm very confused as well. You'd thin kyou can JSON stringify and then TextEncode it to a binary array. I'm just not sure how to do this... – Pete Sep 08 '22 at 15:15
  • 1
    @Pete. 0 At this point you've serialized the object, so the main and worker threads are not SHARING the same object. Changes on one side will not be visable on the other side – mark d drake Sep 23 '22 at 23:01