47 lines
1.4 KiB
JavaScript
47 lines
1.4 KiB
JavaScript
// 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
|
|
|
|
// 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
|
|
const __pending = [];
|
|
|
|
// Promise jobs, in order. `head` is the next one, so that taking a job does
|
|
// not move the others. A job is a closure, which keeps its own data: the
|
|
// handler and the value that it is called with. So each handler gets only the
|
|
// values of its own promise (see `docs/model.md`, section 3.3)
|
|
const __microtasks = { jobs: [], head: 0 };
|
|
|
|
function __queue_job(job) {
|
|
__microtasks.jobs.push(job);
|
|
}
|
|
|
|
function __drain_microtasks() {
|
|
const q = __microtasks;
|
|
|
|
while (q.head < q.jobs.length) {
|
|
const job = q.jobs[q.head];
|
|
q.jobs[q.head] = undefined;
|
|
q.head++;
|
|
job();
|
|
}
|
|
|
|
q.jobs.length = 0;
|
|
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);
|
|
}
|
|
}
|