Race Conditions Without Atomics
You'll learn how concurrent reads and writes to shared memory can produce incorrect, unpredictable results when multiple workers access the same data simultaneously.
The Problem
When multiple workers share a SharedArrayBuffer, they can all read from and write to the same memory locations at the same time. Without coordination, these simultaneous operations create race conditions—situations where the final result depends on unpredictable timing of operations.
Think of it like two people editing the same physical document simultaneously. If both read "5", add 1, and write back "6", the document ends up with "6" instead of the correct "7"—one update was lost.
How It Happens
Consider this scenario with a shared counter:
Thread A: Read value (0) → Add 1 → Write back (1)
Thread B: Read value (0) → Add 1 → Write back (1)
If both threads read before either writes, they both see 0. Both calculate 1. Both write 1. The counter is now 1, not 2.
This is called a read-modify-write race. The operations aren't atomic (indivisible), so other threads can interfere mid-operation.
Why This Matters
Without proper synchronization:
- Counters increment incorrectly
- Shared state becomes corrupted
- Results vary between runs (non-deterministic)
- Bugs are nearly impossible to reproduce reliably
You can't simply use normal JavaScript operations like array[0] = array[0] + 1 on shared memory and expect correctness. The gap between reading and writing creates a vulnerability window.
Key Takeaway:
Concurrent access to SharedArrayBuffer without atomics leads to race conditions where simultaneous read-modify-write operations overwrite each other, producing incorrect and unpredictable results.