Port Authority

The isolated room

This page is cross-origin isolated, which is the price of SharedArrayBuffer. In return, a port can carry memory that both ends see at once, and a thread can stop and wait on it.

Block on a port: a synchronous call with no await

The worker runs three lines of plain blocking code. Each ask() posts the question down a port along with a small piece of shared memory, then sleeps on that memory. Whoever holds the other end of the port writes the answer into it and wakes the worker. The worker never yields, so it cannot receive a message. It does not need to: the answer is already in its memory when it wakes. The other end can be you, or another worker doing slow asynchronous work, and the blocking code cannot tell.

// in the worker: no async, no await, no callback
function ask(question) {
  const memory = new SharedArrayBuffer(516);
  port.postMessage({ question, memory });
  Atomics.wait(new Int32Array(memory, 0, 1), 0, 0);   // stops here
  return read(memory);
}
const name = ask("What is your name?");

// whoever holds the other end, whenever they are ready
write(memory, "Ada");
Atomics.notify(new Int32Array(memory, 0, 1), 0);

Why this matters

  • Code compiled from C, Python or anything else that expects blocking calls can run in a worker and reach asynchronous browser APIs, other workers, other origins or a person, through one port.
  • The port decides who answers. Hand the other end to someone else and the blocked code is now waiting on them. It is the same introduction as everywhere else on this site.
  • Shared memory only crosses to contexts on the same site in the same isolated group. The question can be passed on to another origin over an ordinary port, and the answer written into the memory by whoever passed it on.
  • An isolated page cannot hold a reference to a window on a page that is not isolated, so it cannot open your hub's picker and get an answer back. That is why this is a room of its own.