Use case: a WebWorker calculates some results which are displayed by the main thread, every frame (60fps). The most recently calculated result is ideally what gets displayed in the main thread. I am seeking options that DO NOT COPY buffers. Options:
-
At first glance, a
SharedArrayBuffer
seems the most performant fit for this. One thread writes, the other reads, there can be no race conditions, and there are no copies. The pros are clear. There are some cons (security, use ofAtomics
). -
OTOH we have transferable
ArrayBuffer
s, which, besides being simpler to use, benefit as follows:
when an ArrayBuffer is transferred between threads, the memory
resource that it points to is literally moved between contexts in a
fast and efficient zero-copy operation.
My question therefore is threefold:
-
If using a
SharedArrayBuffer
, how can I avoid “tearing” in the display by rendering buffer data when it has only been partially written by the Worker? Or is this exact problem already solved by the use of Atomics forSharedArrayBuffer
s? If so, how would that look (in code, roughly speaking)? -
As regular
ArrayBuffer
s are cheaply transferable with a zero-copy context-switch of theArrayBuffer
to another Worker, then the only downside is that we must have two transferibleArrayBuffer
s which we flip between: one for current state to be rendered by the main thread, and one for the pending state; at any given moment, one buffer is the property of the writer, and the other is the property of the reader, because eachArrayBuffer
can only be the property of one thread at a time. Does this solution make sense? Could flipping be synchronised? -
Consequently, which would you recommend using in my specific use case?
1