ECMAScript's memory model (ES2017, with SharedArrayBuffer and Atomics) defines what shared-memory reads may return when several agents (workers, the main thread) run at once. It's axiomatic: constraints on event orderings, not an algorithm.
Two kinds of access exist:
- Atomic (
Atomics.load,store,add,compareExchange, …): sequentially consistent (SeqCst). All agents agree on one total order of them. There's nothing weaker such as acquire/release. - Data (plain
view[i]reads and writes): unordered between agents.
Ordering comes from happens-before: program order within an agent (agent-order), plus synchronizes-with edges. A SeqCst write synchronizes-with a SeqCst read of the same range that reads its value; hosts add their own edges, such as sending a buffer with postMessage or starting and stopping a worker.
Two accesses race when neither happens-before the other and they are either two writes to overlapping bytes, or a read and the write it reads from. The race is a data race unless both are atomic with identical ranges.
The guarantees:
- Data-race-free programs are sequentially consistent. Every execution looks like some interleaving of each agent's steps. That's the model to program to.
- Racy programs still have no undefined behaviour. Unlike in C++, a racing read can't return arbitrary garbage or break the engine. It returns bytes that some write to that location produced (or the initial zeros), though not necessarily the latest, and different agents may disagree on order.
- Aligned integer accesses don't tear. A racing read through an integer typed array gets all its bytes from one of the equal-sized writes; float arrays and
DataViewmay mix bytes.
So x++ on shared memory loses updates (read, add, write can interleave), and a plain flag can't safely publish other data. Use Atomics for the flag or counter; that's what creates the happens-before edge.