Files
unkernel/js/web/web-cpu-entry.ts
Pooya Parsa 70a0e0a82e SDK: send every CPU's console output through a shared ring
With more than one CPU, each CPU's fd_write puts its bytes into one
shared ring (js/core/console-ring.ts), reserving its place inside the
import, so the ring keeps the kernel's order. With the shared transport
the owner reads it (Atomics.waitAsync), independent of CPU 0, and a full
ring makes writers wait; inline and with --worker=messages CPU 0's host
reads it, and another CPU that finds it full posts the records as a
numbered batch instead of waiting for CPU 0.

Output from a secondary CPU no longer arrives as one message per write
nor waits for CPU 0 to suspend: seq 1 200000 on CPU 1 takes as long as
on CPU 0, and a shell on CPU 1 echoes in under a millisecond while CPU 0
runs user code (10 ms before).

ConsoleOutput's unread backlog dropped old chunks with Array.shift(),
which copied a long array per chunk: drop them by index.
2026-11-17 14:02:29 +00:00

22 lines
1.1 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// A secondary CPU's thread in browsers (started by cpu.ts): run it
// (core/cpu.ts) with what the first message brings. It finds nothing
// through import.meta.url: in the package it runs from a Blob URL. The
// build bundles it into a module that imports nothing.
import { runCpu, type CpuInit, type CpuMessage } from "../core/cpu.ts";
/** The dedicated worker's global (the page's tsconfig has no webworker lib). */
const scope = globalThis as unknown as {
postMessage(msg: CpuMessage, transfer?: ArrayBuffer[]): void;
addEventListener(type: "message", fn: (e: MessageEvent<CpuInit>) => void, opts: { once: true }): void;
};
scope.addEventListener("message", (e) => {
const init = e.data;
const post = (msg: CpuMessage, transfer?: ArrayBuffer[]) => scope.postMessage(msg, transfer);
// runCpu() reports its own failures; this catches anything it did not
// (a browser's worker reports no unhandled rejection to its owner).
runCpu(init, { post }).catch((err: unknown) => post({ t: "fatal", msg: `CPU ${init.cpu}: ${(err as Error)?.stack ?? err}` }));
}, { once: true });