JavaScriptHard
What is Atomic operation in JS?
Atomic operations, provided by the global Atomics object, read and modify values in a SharedArrayBuffer as single, indivisible steps, so concurrent threads cannot see half-finished updates or lose each other's writes.
The problem they solve
view[0]++ is really three steps: read, add, write. Two workers doing it at the same time can both read 5 and both write 6, losing an increment. Atomics.add(view, 0, 1) performs the whole read-modify-write as one step.
Main operations
- Arithmetic and bitwise:
add,sub,and,or,xor; each returns the old value. - Read/write:
load,store(with ordering guarantees normal reads/writes don't have). exchange: set a new value, return the old one.compareExchange(view, i, expected, replacement): replace only if the current value equalsexpected. This is the building block of locks and lock-free algorithms.- Synchronisation:
Atomics.wait(view, i, value, timeout)blocks a worker until notified (not allowed on the browser main thread);Atomics.notify(view, i, count)wakes waiters;Atomics.waitAsyncgives a promise-based wait usable on the main thread.
Typical uses
Counters and statistics shared between workers, mutexes and semaphores, producer/consumer queues in shared memory, and WebAssembly threads.
Rules
- Atomics work on integer typed arrays (
Int32Arrayand friends, plusBigInt64Array) over aSharedArrayBuffer(most operations also accept normal buffers, but are only meaningful when shared). - Keep shared-memory code small and well tested; it is easy to introduce deadlocks and subtle bugs.
Code example
js
1const view = new Int32Array(new SharedArrayBuffer(16));23// Read-modify-write as one indivisible step (returns the OLD value)4console.log(Atomics.add(view, 0, 5), Atomics.load(view, 0)); // 0 55console.log(Atomics.sub(view, 0, 2), Atomics.load(view, 0)); // 5 36console.log(Atomics.exchange(view, 0, 100), view[0]); // 3 10078// compareExchange: the building block of locks9const UNLOCKED = 0, LOCKED = 1;10function tryLock(v, i) {11 return Atomics.compareExchange(v, i, UNLOCKED, LOCKED) === UNLOCKED; // true if we got it12}13function unlock(v, i) {14 Atomics.store(v, i, UNLOCKED);15 Atomics.notify(v, i, 1); // wake one waiting worker, if any16}1718console.log(tryLock(view, 1)); // true - acquired19console.log(tryLock(view, 1)); // false - already held20unlock(view, 1);21console.log(tryLock(view, 1)); // true - acquired again2223// Why it matters: simulate interleaved non-atomic increments losing an update24const plain = new Int32Array(1);25const a = plain[0]; // thread A reads 026const b = plain[0]; // thread B reads 027plain[0] = a + 1; // A writes 128plain[0] = b + 1; // B writes 1 -> one increment lost29console.log("non-atomic result:", plain[0]); // 1 (should be 2)3031const safe = new Int32Array(new SharedArrayBuffer(4));32Atomics.add(safe, 0, 1);33Atomics.add(safe, 0, 1);34console.log("atomic result:", Atomics.load(safe, 0)); // 2
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.