Rust/wasm32: is SharedArrayBuffer ever useful?

For those using Rust on wasm32 (say Chrome), is there any time where SharedArrayBuffer is useful?

In all cases I have examined so far, usage of js_sys::SharedArrayBuffer can be replaced by js_sys::ArrayBuffer.

My understanding is that a SharedArrayBuffer can be shared between multiple web workers running in parallel.

1 Like

To the best of my knowledge, yes. However, to the best of my knowledge:

  • there aren't any synchronization primitives over SharedArrayBuffer

  • in Rust/wasm, the only useful commands over SharedArrayBuffer are copy to vec / copy from slice; and even here, it is not clear what guarantees there are

So I am having a difficult time thinking of situations where SharedArrayBuffer is useful (maybe some external sync to say web worker thread 1 writes to first 10MB, web worker thread 2 writes to 2nd MB, ...) but in these cases, it's not obvious why not use ArrayBuffer instead with zero copy:

Transferrable objects are commonly used to share resources that can only be safely exposed to a single JavaScript thread at a time. For example, an ArrayBuffer is a transferrable object that owns a block of memory. When such a buffer is transferred between threads, the associated memory resource is detached from the original buffer and attached to the buffer object created in the new thread. The buffer object in the original thread is no longer usable because it no longer owns a memory resource.

Quoting:

The following guide seems to clarify a bunch of things:

This is thus the culprit: the API of SharedArrayBuffers that ends up being exposed from within Rust does not include the actual usefulness of them; I guess because of browser compatibility (SABs have remained disabled for a few years due to spectre-related memory leakage and security implications; it's only somewhat recently that a new generation of SABs robust to these issues is being released, thus bringing back support for them).

1 Like

There are. It supports a futex like api and if you compile the sysroot with atomics support, this will be used to implement Mutexes and other synchronization primitives.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.