SharedArrayBuffer
- Node.js course
- Advanced
- Lesson 11/83
- 5 min
Learn shared memory with SharedArrayBuffer.
SharedArrayBuffer
SharedArrayBuffer is a block of memory shared between threads. postMessage copies data; SharedArrayBuffer shares the same memory directly. This removes the copy cost for large data.
When you create a SharedArrayBuffer and send it via postMessage, both sides read and write the same memory. To prevent concurrent write races you use the Atomics object. This is a powerful tool for low-level parallel programming.
Safe access with Atomics
Multiple threads can write to shared memory at the same time; this causes race conditions. The Atomics object provides safe read-write and synchronization primitives.
For example Atomics.store(arr, index, value) does an atomic write; Atomics.load(arr, index) does an atomic read. There are also Atomics.add, Atomics.compareExchange and more. These are the foundation of lock-free programming.
Practice Log the byteLength value
Create a SharedArrayBuffer of 8 bytes. Log sab.byteLength.
Starter code
// Create an 8-byte SharedArrayBuffer
// log the byteLength valueSample solution
const sab = new SharedArrayBuffer(8);
console.log(sab.byteLength);Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the class name
const sab = new ____(8)
const sab = new SharedArrayBuffer(8)
Explanation: new SharedArrayBuffer(8) creates 8 bytes of shared memory.
2 Match each piece to its role
| Term | Meaning |
|---|---|
SharedArrayBuffer |
Shared memory |
Atomics |
Safe access |
sab.byteLength |
Byte size |
new SharedArrayBuffer(8) |
8 bytes |
3 What does SharedArrayBuffer provide?
- A new child process
- A network connection
- Memory shared between threads Correct answer
- File system access
Explanation: SharedArrayBuffer provides shared memory between threads.