Will
Will

Reputation: 1

Visibility of data in shared array buffer after using postMessage() with web worker

I am using a web worker to process some data for me. The flow goes like this: main thread writes to a shared array buffer, then once done writing, uses postMessage to send the buffer to the webworker. The main thread then waits (does not read from or write to the buffer) until receiving a message back from the worker. The web worker upon receiving the message with the shared array buffer reads the data, does some processing, writes the processed data to the shared array buffer, then uses postMessage to post the shared array buffer back to the main thread. The main thread upon receiving the message, reads from the buffer.

My question is, does postMessage guarantee that the shared array buffer has up to date information visible on the worker and main threads without using atomics? I know atomics are needed for simultaneous read and writes, but in my case there are no simultaneous read and writes, and my understanding is that postMessage ensures that the state of the data at that point in time is made up-to-date and visible on the receiving end without needing atomics. Is my understanding correct?

In the application, the reading and writing is performance critical, so while I know using atomics for each read and write will for sure work, if I can avoid the overhead of atomics that would be ideal.

Upvotes: 0

Views: 92

Answers (1)

Kaiido
Kaiido

Reputation: 136698

Atomics are needed when you may have simultaneous read/write operations from different agents. For a single agent, the read/write operation is synchronous. So indeed, if you do signal the other end through postMessage() that the data has been updated, you can be sure that at the time this call is made the data write has been made, and moreover at the time the agent receives the message and handles it.

However, if you don't wait for the other end to let you know it's done reading, before writing new data, you can be sure in what state the buffer will be. Also, if "the reading and writing is performance critical" as you say, note that signaling through postMessage() will be slower than using Atomics. You go through tasking and have to wait for both contexts to be ready to post / handle the message. Atomics would be faster here. Not that using messaging is bad per se, it will depend on your scenario which is "best".

Upvotes: 0

Related Questions