// Stream B1 (fibers) B1.4a — a truly-SUSPENDING fiber-task async layer // (`go` / `wait` / `cancel`) over the M:1 scheduler, in pure sx. In contrast // with 1805's `context.io.async` (which runs each worker INLINE to completion // before returning a `.ready` future — no interleaving), here `s.go(work)` runs // `work` as a REAL fiber and `t.wait()` SUSPENDS the caller until that fiber // finishes, so a task that yields mid-body lets a sibling task run before the // first completes — genuine cooperative interleaving. // // `work` is a NULLARY thunk: any inputs are captured in the lambda at the call // site (no `..args` pack crosses the fiber boundary — that would hit issue 0156 // Part 2). Outputs flow OUT through pointers captured in the thunk (the shared // `Log` struct), since closure capture-by-value does not write back. // // What this proves: // - REAL suspend + interleave: task A records 1, YIELDS; task B then records 2 // and completes; A resumes, records 3, completes → interleave order 1 2 3. // - awaited VALUES: A returns 42, B returns 100 (recorded after both waits). // → sequence: 1 2 3 42 100. // - cancel rides the `!` channel (model (a), like 1806): a canceled task's // `wait()` raises `.Canceled`, taken by the `or` default → -99. // // `wait` must run inside a fiber (it parks `self.current`), so the "main task" // is itself a `s.spawn(...)` fiber that drives the two `go` tasks. // // aarch64-macOS-pinned (the scheduler's asm + guard-page mmap constants are // per-arch / Apple-specific): runs end-to-end on a matching host, ir-only on a // mismatch. #import "modules/std.sx"; sched :: #import "modules/std/sched.sx"; Log :: struct { seq: [16]i64; n: i64; } rec :: (l: *Log, v: i64) { l.seq[l.n] = v; l.n = l.n + 1; } main :: () -> i64 { lg : Log = .{ n = 0 }; // seq[] zero-filled s := sched.Scheduler.init(); ps := @s; pl := @lg; // The "main task" fiber: drives two real tasks, waits both, then exercises // cancel. It runs as a fiber so `wait` has a `self.current` to park. s.spawn(() => { // Task A yields mid-body so B interleaves before A completes. a := ps.go(() -> i64 => { rec(pl, 1); ps.yield_now(); // suspend A; B (already spawned) runs to completion rec(pl, 3); 42 }); // Task B runs straight through (no yield). b := ps.go(() -> i64 => { rec(pl, 2); 100 }); // Wait both — suspends the main-task fiber until each completes. va := a.wait() or { -1 }; vb := b.wait() or { -1 }; rec(pl, va); rec(pl, vb); // Cancel case: cancel before the worker runs; `wait` raises .Canceled, // the `or` default (-99) is taken. c := ps.go(() -> i64 => 7); c.cancel(); rec(pl, c.wait() or { -99 }); }); s.run(); // Interleaving + value contract: 1 2 3 42 100, then the cancel default -99. print("sequence:"); i := 0; while i < lg.n { print(" {}", lg.seq[i]); i = i + 1; } print("\n"); print("spawned: {}\n", s.n_spawned); return 0; }