Course contentsShow
← JavaScript
Lesson 2187 of 2,72345. Workers and ConcurrencyFree lesson

Atomics.wait and Atomics.notify

Block a worker until notified, enabling synchronization patterns like mutexes and condition variables.

Atomics.wait and Atomics.notify

You'll learn how to synchronize workers by blocking threads until notified, enabling coordination patterns like locks and semaphores.

The Problem: Workers Need to Wait for Each Other

So far you've seen atomic operations for reading and writing shared memory safely. But sometimes one worker needs to pause and wait until another worker signals that something is ready—like waiting for a shared resource to become available or for data to be processed.

How Atomics.wait and Atomics.notify Work

Think of Atomics.wait like a worker hitting a "pause button" until someone else hits the "play button" with Atomics.notify.

Atomics.wait(typedArray, index, expectedValue, timeout) blocks the current thread if the value at typedArray[index] equals expectedValue. The worker sleeps until:

  • Another thread calls Atomics.notify on that same index
  • The timeout expires (optional, in milliseconds)
  • The value changes

Atomics.notify(typedArray, index, count) wakes up count workers waiting on that index (or all if count is omitted/Infinity).

Real-World Analogy

Imagine a ticket booth (shared memory location). Workers line up and wait if the "OPEN" flag shows the expected "CLOSED" value. When the booth opens, the manager calls out to wake waiting workers—that's notify.

Simple Coordination Example

// Shared between main thread and worker
const sharedBuffer = new SharedArrayBuffer(4);
const sharedArray = new Int32Array(sharedBuffer);

// Worker waits for value to change from 0
Atomics.wait(sharedArray, 0, 0); // Blocks here!
console.log('Notified! Value is now:', Atomics.load(sharedArray, 0));

// Main thread signals
Atomics.store(sharedArray, 0, 1);
Atomics.notify(sharedArray, 0, 1); // Wake 1 waiter

Key Takeaway: Atomics.wait blocks a worker thread until Atomics.notify is called, enabling synchronization primitives like mutexes and condition variables for coordinating concurrent work.