Invert event loop

This commit is contained in:
2026-10-08 08:53:11 +00:00
parent c4d0bab3d9
commit 2f21347088
12 changed files with 142 additions and 33 deletions
+3 -2
View File
@@ -1,2 +1,3 @@
// Runs after the program: the event loop (see loop.js)
__run_loop();
// Runs after the program's top level: its microtasks. The host then runs
// the event loop (see loop.js)
__drain_microtasks();
+13 -16
View File
@@ -1,8 +1,8 @@
// The event loop. A macrotask is an IO op or a timer, which completes in C
// (see lib/rt/io.h): `__native_io_wait()` gives the handle of the next one
// that completes. A microtask is a promise job, in `__microtasks`. After the
// program, end.js runs the loop: all microtasks, then one macrotask, then all
// microtasks again, until nothing is pending
// The event loop's JS side. The host owns the loop (see lib/rt/jsrt.h). A
// macrotask is an IO op or a timer, which the host runs: it calls
// `__complete(h)` when op `h` is done. A microtask is a promise job, in
// `__microtasks`. After the program's top level, end.js runs all microtasks,
// and after each macrotask, `__complete` does
// What to do when IO op `h` completes: `__pending[h]`, a fn that gets `h`.
// Handles are small ints, and a handle is used again after its op completes
@@ -32,15 +32,12 @@ function __drain_microtasks() {
q.head = 0;
}
function __run_loop() {
for (;;) {
__drain_microtasks();
const h = __native_io_wait();
if (h < 0) return;
const done = __pending[h];
__pending[h] = undefined;
if (done !== undefined) done(h);
}
// What the host calls when op `h` is done: its callback, then the microtasks
function __complete(h) {
const done = __pending[h];
__pending[h] = undefined;
if (done !== undefined) done(h);
__drain_microtasks();
}
__link_host_complete(__complete);