← Lessons

quiz vs the machine

Platinum1800

Concurrency

Shared Array Buffer And Atomics

Genuine shared memory between threads, made safe with atomic operations that prevent torn reads and races.

6 min read · advanced · beat Platinum to climb

Actually sharing memory

Message passing copies data, which is wasteful for large hot structures. A shared array buffer is a block of memory that multiple threads can read and write directly, no copying. This unlocks real shared memory parallelism, but reintroduces the dangers that isolation avoided.

The race problem

When two threads touch the same location without coordination, you get data races. Reads can observe partial writes, and increments can be lost when two threads read, add, and write back over each other. The hardware and compiler may also reorder operations in surprising ways.

Atomics restore order

Atomic operations make specific reads and writes indivisible and ordered.

  • An atomic read or write completes wholly, never torn.
  • An atomic add or compare and swap lets threads update shared values safely.
  • Atomic wait and notify let a thread sleep until another signals, a building block for locks.

Atomics also establish a memory ordering so threads agree on what happened before what. Use them around any shared mutable location.

Key idea

A shared array buffer gives threads direct shared memory, and atomic operations make individual accesses indivisible and ordered, preventing torn reads and lost updates that plague unsynchronized sharing.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a shared array buffer provide?

2. Why are atomic operations needed on shared memory?

3. What does atomic wait and notify enable?