Sub topic 3
Non-Blocking Waits with Atomics.waitAsync
This chapter assumes you already know Atomics.wait, Atomics.notify, and Atomics.compareExchange from the previous chapter.
Waiting Without Blocking
Atomics.wait blocks the thread that calls it, so browsers do not allow it on the main thread. Atomics.waitAsync returns a result object instead. When async is true, value holds a Promise that settles when another thread calls notify or the timeout expires.
const flag = new Int32Array(new SharedArrayBuffer(4));
const result = Atomics.waitAsync(flag, 0, 0, 1000);
if (result.async) {
result.value.then((outcome) => console.log(outcome)); // 'ok' or 'timed-out'
} else {
console.log(result.value); // 'not-equal' or 'timed-out'
}Building a Mutex
A mutex claims a lock slot with compare-and-swap and sleeps while another thread holds it. Because Atomics.wait blocks, use this mutex in workers only.
const UNLOCKED = 0;
const LOCKED = 1;
function lock(i32, index) {
while (Atomics.compareExchange(i32, index, UNLOCKED, LOCKED) !== UNLOCKED) {
Atomics.wait(i32, index, LOCKED);
}
}
function unlock(i32, index) {
Atomics.store(i32, index, UNLOCKED);
Atomics.notify(i32, index, 1);
}Memory Ordering
All Atomics operations are sequentially consistent: every thread observes them in one shared order. Suppose thread A writes plain data and then calls Atomics.store on a flag. If thread B's Atomics.load sees that flag value, B is guaranteed to see A's earlier writes. This is the happens-before guarantee. Without the atomic flag, B might read stale data.
A Single-Producer Single-Consumer Ring Buffer
A ring buffer keeps a fixed data array plus two atomic indices. Only the producer advances write, and only the consumer advances read. The producer writes the item first and then publishes it with Atomics.store on write. The consumer reads write with Atomics.load before it reads the item. Because each index has a single writer, the buffer needs no lock. When the buffer is empty, the consumer can sleep with Atomics.wait on the write index.
Lock-Free Sizes and Growable Buffers
Atomics.isLockFree(n) reports whether atomic operations on n-byte elements avoid an internal lock. Atomics.isLockFree(4) is always true, so Int32Array is the safest choice.
A growable buffer is created with a maximum size, and it can grow but never shrink:
const sab = new SharedArrayBuffer(8, { maxByteLength: 64 });
sab.grow(16);
console.log(sab.byteLength, sab.growable); // 16 trueShared Memory or Message Passing?
| Factor | Shared memory | postMessage |
|---|---|---|
| Data copying | None | Copies the data (or transfers ownership) |
| Race risk | High, needs Atomics | None |
| Browser setup | Needs COOP and COEP | None |
| Best for | Hot loops, large buffers, low latency | Most app messaging |
Start with message passing. Move to shared memory when profiling shows that copying data or message latency is the bottleneck.
Exercise
Why does the ring buffer's producer write the item before calling Atomics.store on the write index?
Show answer
The atomic store publishes the item. Any consumer whose Atomics.load sees the new index is guaranteed to also see the item written before the store. If the order were reversed, the consumer could read a slot that has not been filled yet.
Exercise
Your browser main thread must wait for a worker to set a flag. Which API do you use, and why?
Show answer
Use Atomics.waitAsync. Atomics.wait is not allowed on the browser main thread because it would block rendering and input. waitAsync returns a Promise instead.