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!

6
  • 2
    No. (Shared)ArrayBuffers hold binary data, not objects. Commented Mar 16, 2022 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. Commented Mar 16, 2022 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. Commented Mar 16, 2022 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. Commented Mar 16, 2022 at 21:57
  • 2
    There is this project you may want to have a look at. Commented Mar 17, 2022 at 14:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

can't you convert the Object to binary and vice-versa in the Worker?
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. 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

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.