.nib std
nib 0.3.1-pre

Pre-release documentation. This describes nib 0.3.1-pre, which is on main and has no release yet: what it documents beyond 0.3.0 may change before it ships.

module use "std/sched.nib"

Sched

The schedule: Sched.Policy.pick decides which ready fibre runs next. Bind it in a wire to an effector of your own; leave it unbound for the runtime's FIFO queue.

Sched has one interface, Sched.Policy, with one operation. A wire that binds it hands the runtime's one scheduling decision to an effector the program writes; a wire that does not gets a FIFO queue, first come, first served.

No function names Sched.Policy in its effect row. An effect row says what a function may ask, and no function asks the policy anything: the runtime calls pick when two or more fibres are ready, and a program cannot. The wire chooses the schedule the way it chooses which clock or which network a program gets.

use "std/sched.nib"
use "std/time.nib"
use "std/io.nib"

effector Newest is Sched.Policy where
  pick(ready) = Vec.size(ready) - 1

module Order where
  func say :: name: String -> () ! Time.Clock, Io.Print =
    let _ = @Io.Print.println(name ++ " starts");
    let _ = @Time.Clock.sleep(1);
    @Io.Print.println(name ++ " ends")

  func main :: -> () ! Time.Clock, Io.Print raises HandleRefused =
    Switch.run { sw ->
      let a = fork(sw) { -> say("a") };
      let b = fork(sw) { -> say("b") };
      let _ = Fiber.await(a);
      Fiber.await(b)
    }

wire W runs Order.main where
  Time.Clock = Time.Sim, Io.Print = Io.Stdout, Sched.Policy = Newest
b starts
a starts
a ends
b ends

Under the queue a starts first; under Newest, b does. A policy is for testing an order the queue never produces, and each pick it makes is written to the journal as a World.schedule entry, so the run replays without it. A compiled program runs its host's own queue, and nibc build refuses a wire that binds a policy rather than ignore it.

Interfaces

interfacePolicy
interface Policy where
  pick(ready: Vec<Int>) -> Int

One decision. pick(ready) is asked whenever two or more fibres are ready: ready holds them by the numbers the journal gives them (the run's own thread is 0), in the queue's order, and the answer is an index into it, so 0 is the fibre the queue would have run. An answer that is not an index ends the run.

The body decides from ready and the effector's own vars and nothing else: it may not wait, fork, raise, or perform an effect of its own, because its answer is the only thing the journal records of it. Fairness is the policy's to keep: one that never picks a fibre starves it.

use "std/sched.nib"

effector Alternate is Sched.Policy where
  unkeyed var turn :: Int = 0;
  pick(ready) =
    let t = turn;
    (turn := t + 1;
     if t % 2 == 0 then 0 else Vec.size(ready) - 1)

module Main where
  func main :: -> Int = 1

wire W runs Main.main where Sched.Policy = Alternate