简体   繁体   中英

Can you store a JS object in a SharedArrayBuffer?

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!

No, SharedArrayBuffer s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM