Atomics.load and Atomics.store
You'll learn how to safely read and write SharedArrayBuffer data without race conditions.
The Problem with Regular Access
When multiple workers directly read or write to a SharedArrayBuffer using bracket notation, the JavaScript engine doesn't guarantee that operations complete without interference. One worker might read a value while another is halfway through writing it, leading to unpredictable results—classic race conditions.
Thread-Safe Reads and Writes
Atomics.load() and Atomics.store() are your safeguards. They ensure that reads and writes happen atomically—meaning the operation completes entirely before any other thread can interfere.
Atomics.load(typedArray, index) safely reads a value from a shared array at the specified index. It guarantees you get a complete, coherent value, not a partially-written one.
Atomics.store(typedArray, index, value) safely writes a value to a shared array. Other workers won't see intermediate states; they'll either see the old value or the new one, never something in-between.
The Analogy
Think of SharedArrayBuffer as a whiteboard in a conference room. If two people try writing at the same spot simultaneously (regular access), you might see overlapping, illegible scribbles. Atomics.store() is like grabbing a marker lock—you write completely before releasing it. Atomics.load() is like waiting for complete letters before reading—no half-written characters.
When to Use Them
Always use Atomics.load() and Atomics.store() when accessing SharedArrayBuffer data across workers. They prevent the race conditions you learned about in the previous lesson, ensuring your concurrent code behaves predictably.
Key Takeaway: Use Atomics.load() for thread-safe reads and Atomics.store() for thread-safe writes to SharedArrayBuffer—they guarantee atomic operations that won't be interrupted by other workers.