Module 45 // Core JavaScript

Shared Memory & Atomics

Module Objective

SharedArrayBuffer, Atomics operations, synchronization

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Creating Shared Memory
const sab = new SharedArrayBuffer(4); // 4 bytes
const view = new Int32Array(sab);

// Pass sab to a Worker...
// worker.postMessage(sab);
💡 Unlike regular `ArrayBuffer` which is copied or transferred, a `SharedArrayBuffer` allows both the main thread and the worker to access the same physical bytes in RAM.
// Example 2
// 2. The Race Condition Problem
// Thread A: val = val + 1
// Thread B: val = val + 1

// Without Atomics, they might both read 0 at 
// the same time and write 1, losing an increment!
💡 Race conditions happen when two threads try to modify memory at once. The result depends on which thread's CPU cycle finishes first.
// Example 3
// 3. Solving with Atomics
const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);

// Thread-safe increment
Atomics.add(view, 0, 1);
💡 `Atomics.add` ensures that the Read-Modify-Write cycle happens as a single atomic operation that cannot be interrupted by another thread.

Engine & Memory Architecture

Hardware & Threads

1. CPU Memory Barriers:

  • Atomics use hardware-level Memory Barriers to ensure that all CPU cores see the same value in their local caches.

2. Physical RAM:

  • The SharedArrayBuffer maps to a single physical location in RAM.
  • All threads have a pointer to this identical address in the Heap.

3. Safety (Spector/Meltdown):

  • Shared memory was temporarily disabled in browsers due to hardware security vulnerabilities.
  • Modern browsers require Cross-Origin Isolation (COOP/COEP headers) to use SharedArrayBuffer safely.