MDN self-hosted library · e01.org
Atomics.pause() / notebook

Atomics.pause()

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
// Imagine another thread also has access to this shared memory
const sab = new SharedArrayBuffer(1024);
const i32 = new Int32Array(sab);

function lock() {
  while (true) {
    // Fast path: spin the CPU for a short while
    let spin = 0;
    do {
      if (Atomics.compareExchange(i32, 0, 0, 1) === 0) {
        return;
      }
      Atomics.pause();
      spin++;
    } while (spin < 10);

    // Slow path: wait for the lock
    // This can only be called in a worker thread,
    // because the main thread cannot be blocked
    Atomics.wait(i32, 0, 1);
  }
}