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.