Question presented to candidate: "Normally, when a Web Worker and the main thread talk via postMessage, the data gets copied — each side has its own separate version. How would you let two workers genuinely share the SAME block of memory, so a write on one side is immediately visible on the other without any copying or messaging round trip? And once they can both touch the same memory, what specifically goes wrong if you are not careful?"
What a strong answer should cover:
SharedArrayBufferallocates a raw binary buffer whose memory is genuinely shared (the same physical bytes) across the main thread and any worker it is handed to — unlike a regularArrayBuffersent throughpostMessage, which is either copied (structured clone) or transferred (moved, single-owner) but never simultaneously owned by both sides.- A typed array (
Int32Array,Float64Array, etc.) is used as a view onto that shared memory — theSharedArrayBufferitself is just raw bytes; reading and writing happens through the view. - Because two threads can now touch the same memory at the same instant, a plain
value = value + 1on a shared cell is NOT atomic — it is a real read-modify-write sequence with a gap in the middle where another thread's write can be silently lost. This is a genuine race condition, not a theoretical one. Atomics(Atomics.add,Atomics.load,Atomics.store,Atomics.compareExchange) provides real atomic read-modify-write operations that close that gap, plusAtomics.wait/Atomics.notifyfor actual thread synchronization (blocking a worker until signaled).- A candidate should name the real-world browser restriction:
SharedArrayBufferrequires a cross-origin-isolated page (COOP/COEP response headers) since the 2018 Spectre-driven disable — it is not simply "available" on every page the wayArrayBufferis. - A strong answer distinguishes this from Node.js
worker_threads, which exposes the identicalSharedArrayBuffer/Atomicsmechanism without that browser header requirement, since Node has no cross-origin page-isolation model to protect.
Clarifying questions expected:
- "Is this for a real browser deployment, where the cross-origin-isolation header requirement genuinely applies, or for a Node.js worker_threads context, where it does not?" — changes whether COOP/COEP setup is actually part of the real answer.
- "Does the shared data need to grow, or is a fixed-size buffer acceptable?" — affects whether a growable SharedArrayBuffer (a newer, distinct capability) is relevant.
Code / implementation expected: Yes — a real, runnable demonstration of the race (a lost-update count) and the Atomics-based fix (zero lost updates) is the concrete way to prove the concept, not just describe it.