module always in scope
Fiber
A handle to a task started with fork inside a Switch.run scope. Fiber.await waits for it to finish.
A Fiber is a lightweight task. Fibres run concurrently on one executor, taking turns — they are not threads, and they do not run on separate cores.
Fibres are started inside a scope. Switch.run { sw -> … } opens one and hands its body a Switch; inside, fork(sw) { -> … } queues a new fibre and immediately answers its Fiber handle. A fibre's body takes no arguments, answers (), and may not raise. Switch.run answers whatever its body answers, and it does not return until every fibre forked under it has finished, so no fibre outlives the scope that started it.
Switch.run { sw ->
let _ = @Io.Print.print("1 ");
let f1 = fork(sw) { -> @Io.Print.print("2 ") };
let _ = @Io.Print.print("3 ");
let f2 = fork(sw) { -> @Io.Print.print("4 ") };
let _ = Fiber.await(f1);
let _ = Fiber.await(f2);
"done"
}
1 3 2 4 done
fork does not run the fibre straight away: it joins the back of a first-in, first-out queue, and the caller keeps running. Queued fibres run when the current one waits — on Fiber.await, or on an operation that parks, such as a sleep or a socket read. That is why 1 and 3 print before 2 and 4 above. Performing an effect that does not wait does not switch fibres.
A fibre that is never awaited still runs: the end of Switch.run is itself a wait for every fibre in the scope.
let answer = Switch.run { sw ->
let _ = fork(sw) { -> @Io.Print.print("from the fibre; ") };
"from the body"
};
answer
from the fibre; from the body
A Fiber has no literal. It prints as Fiber(<n>), a diagnostic number, compares with == by identity, and can be stored in a Vec or a Map, but Json.render refuses it.
Switch.run { sw ->
let f = fork(sw) { -> () };
let g = fork(sw) { -> () };
(#[f, g], f == f, f == g)
}
(#[Fiber(3), Fiber(4)], true, false)
Functions
func await :: Fiber -> () raises HandleRefused
Waits until the fibre f has finished. While the caller waits, the other queued fibres run. Awaiting a fibre that has already finished answers () at once, so awaiting the same fibre twice is fine.
A fibre that cannot finish is refused with HandleRefused, which Fiber.await raises: one that was killed (a crash in the simulated world kills every fibre of a host), or one whose Switch.run has already returned. The raise is in await's type, so a function that awaits declares raises HandleRefused or rescues it — a supervisor rescues it to notice that what it was waiting on died.
Switch.run { sw ->
let f = fork(sw) { -> @Io.Print.print("child ran, ") };
let _ = Fiber.await(f);
let _ = Fiber.await(f);
"awaited twice"
}
child ran, awaited twice