Question presented to candidate: "Atomics.wait() blocks the calling thread until another thread calls Atomics.notify() on the same location. Why can that be a problem, and how does Atomics.waitAsync() solve it? Walk through what its return value actually looks like, and what happens on Node's main thread specifically versus a browser's main thread."
What a strong answer should cover:
- Atomics.wait(typedArray, index, value, timeout) blocks the calling thread's execution entirely until another thread calls Atomics.notify() on that exact index, or the timeout elapses — nothing else on that thread runs while blocked, including timers and I/O callbacks.
- Atomics.waitAsync() returns synchronously and immediately, shaped { async: boolean, value }. If the current value already differs from the expected one, it returns { async: false, value: "not-equal" } with no promise involved. Otherwise it returns { async: true, value: aPromise } that resolves to "ok" or "timed-out".
- In BROWSERS, Atomics.wait() throws a TypeError on the main/UI thread specifically — it is only legal on a Worker there, since blocking the UI thread would freeze the page. Node.js has no such restriction: Node's "main thread" is not a UI thread, so Atomics.wait() is legal there and simply blocks it — verified directly, not assumed.
- waitAsync()'s pending promise does not block the event loop while pending — other code, timers, and I/O keep running normally, verified by a real interleaved setTimeout that fires before the promise resolves.
- SharedArrayBuffer plus Atomics is the actual low-level primitive underneath higher-level constructs like WebAssembly threads and hand-rolled worker pools that need to coordinate without message-passing overhead.
Clarifying questions expected:
- "Does this run in a browser or in Node.js?" — the main-thread-blocking restriction on Atomics.wait() is browser-specific, not a JavaScript-spec-wide rule, and answering as if it always throws is a common but real mistake worth naming explicitly.
- "Is cross-origin isolation (COOP/COEP headers) set up?" — SharedArrayBuffer is disabled by default in browsers without those headers, which silently makes this whole API surface unavailable.
Code / implementation expected: Yes — a real, non-blocking waitAsync() call verified to return immediately, plus a real cross-thread worker_threads example proving the promise resolves only after a genuine Atomics.notify() from another thread.