Suggest an editImprove this articleRefine the answer for “What does SharedArrayBuffer do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`SharedArrayBuffer`** is a special type of buffer holding raw binary data that can be shared between multiple threads (for example, a Web Worker and the main thread) without copying the data. **Key point:** because several threads can read and write the same memory at the same time, safe synchronization requires the `Atomics` object.Shown above the full answer for quick recall.Answer (EN)Image## What `SharedArrayBuffer` is `SharedArrayBuffer` is a special type of buffer that: - holds **raw binary data (bytes)**; - can be **shared** between different threads (for example, a Web Worker and the main thread); - allows **reading and writing the same memory at the same time**; - **does not copy** data on transfer - a *reference* to the same memory region is passed instead. ## Difference from a regular `ArrayBuffer` | Property | `ArrayBuffer` | `SharedArrayBuffer` | | --- | --- | --- | | Used by | A single thread | Multiple threads | | When passed to a worker | Copied, or transferred via `transfer` (becomes inaccessible in the original thread) | Shared - both threads see the same memory | | Can use Atomics | No | Yes (for safe synchronization) | | Thread safety | Not required | Required (via `Atomics`) | ## Example: a shared buffer between threads ### 1. The main thread (main.js) ```javascript // Create a shared buffer of 4 bytes (Int32 = 4 bytes) const sharedBuffer = new SharedArrayBuffer(4); // Wrap it in a typed array const sharedArray = new Int32Array(sharedBuffer); sharedArray[0] = 0; // initial value // Create a worker and pass it the shared buffer const worker = new Worker('worker.js'); worker.postMessage(sharedBuffer); // Watch for changes setInterval(() => { console.log('Main thread value:', sharedArray[0]); }, 1000); ``` ### 2. The worker (worker.js) ```javascript onmessage = (e) => { const sharedArray = new Int32Array(e.data); // Increment the value every 500 ms setInterval(() => { Atomics.add(sharedArray, 0, 1); // atomic increment }, 500); }; ``` Result: ```javascript Main thread value: 0 Main thread value: 2 Main thread value: 4 Main thread value: 6 ... ``` `SharedArrayBuffer` provides **shared memory**, while `Atomics` guarantees **thread safety** (no data races). ## Why `Atomics` is needed Since several threads can read and write the same memory cell at the same time, **race conditions** can occur without synchronization. For this, there is the `Atomics` object, which provides atomic operations: | Method | What it does | | --- | --- | | `Atomics.add(typedArray, index, value)` | Adds a value atomically | | `Atomics.sub()` | Subtracts atomically | | `Atomics.and()` / `or()` / `xor()` | Bitwise atomic operations | | `Atomics.load()` / `Atomics.store()` | Safe read/write | | `Atomics.exchange()` | Sets a new value and returns the old one | | `Atomics.compareExchange()` | Changes the value if the current one matches the expected one | | `Atomics.wait()` / `Atomics.notify()` | Lets you "put a thread to sleep" until the value changes (workers only) | ## Example: synchronization with `Atomics.wait` / `Atomics.notify` ```javascript // main.js const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); const worker = new Worker('worker.js'); worker.postMessage(sharedBuffer); // After 2 seconds, "wake" the worker setTimeout(() => { console.log('Main: notify worker'); Atomics.store(sharedArray, 0, 1); Atomics.notify(sharedArray, 0, 1); }, 2000); ``` ```javascript // worker.js onmessage = (e) => { const sharedArray = new Int32Array(e.data); console.log('Worker: waiting...'); Atomics.wait(sharedArray, 0, 0); // waits until the value changes console.log('Worker: woken up, value:', sharedArray[0]); }; ``` Here the worker literally "sleeps" until the main thread "wakes" it up. This gives **real multithreading** (coordination between JS threads). ## Where `SharedArrayBuffer` is used | Scenario | Use | | --- | --- | | **Web Workers** | Transferring large data without copying | | **Multithreaded computation** | Parallel processing of matrices, graphics, physics | | **Games and simulations** | Updating world state across several threads | | **Machine Learning / WASM** | TensorFlow.js, WebAssembly, OpenCV use `SharedArrayBuffer` | | **Video / audio processing** | Sharing buffers between threads | | **A data bus between workers** | Instant data transfer without JSON serialization | ## Security and limitations (CORS / COOP / COEP) Because of **Spectre vulnerability** risks, browsers enable `SharedArrayBuffer` **only in isolated contexts** (Cross-Origin Isolation). For `SharedArrayBuffer` to work in the browser, you need to set the right headers: ```javascript Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` And make sure all resources (scripts, workers) are also compatible with this mode. ## Example: enabling Cross-Origin Isolation For a dev server (for example, Vite or Express): ```javascript app.use((req, res, next) => { res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); next(); }); ``` Now the browser will allow `SharedArrayBuffer` to be used. ## Summary | Property | Description | | --- | --- | | What it does | Shares memory between threads without copying | | Where it works | In Web Workers and Node.js (worker_threads) | | Requires | `Atomics` for synchronization | | Security | Only with COOP/COEP enabled | | Typical scenarios | Parallel computation, caching, rendering, WebAssembly | | Analog in C/C++ | Shared memory between threads | **The main idea:** > `SharedArrayBuffer` gives JavaScript the ability to do *real parallelism* > - several threads can read and write **the same memory at the same time**, > while `Atomics` ensures **correctness and synchronization**.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.