System.Task
Tasks: functions that run concurrently with the code that started them,
each suspending where it waits -- in join, in yield, at any depth of
ordinary calls -- so that others run meanwhile. They run on a worker per
core, or on as many as the environment's TURKEY_WORKERS asks for: with
one, tasks interleave but never run in parallel, and nothing else runs
between two suspension points of one task, except while it waits in a call
the poller cannot carry -- a file read, flock -- long enough that another
thread takes over running the rest; with more, tasks run in parallel, and
what two of them share needs synchronizing.
Every task belongs to a scope, and a scope ends only when every task started in it has finished:
let (a, b) = runScope(do {
let a = spawn(fun() = fetch("a"))?
let b = spawn(fun() = fetch("b"))?
pure((a, b))
})
print(join(a) + join(b))
The scope is never a value a program can hold. spawn is a Spawn
computation, which only runScope runs, giving it the scope; so a task can
only be started inside a runScope, and no scope outlives its runScope.
A Spawn value carried out of one runs in whichever runScope runs it
next.
Scheduling is cooperative. A task that computes without waiting or yielding holds the worker until it finishes, and there is no cancellation: a scope whose task never finishes never ends. A panic in a task ends the program, as a panic anywhere does; a task's recoverable errors are its result.
A task started by spawn, and its result once it has one.
result is written by the task and read by whoever joins it, so !Debug
keeps a derived Debug from reading it while it runs.
A computation that may start tasks: run by runScope, sequenced with ?.
Run body, then wait for every task it started; the result is body's.
A task's result, and what waits on a task or a scope, are written under
the scheduler's lock (Turkey.Scheduler), which is what makes a result
one task writes visible to the task that joins it on another worker.
Start f as a task in the enclosing scope. It runs when the code that
started it next waits or yields.
task's result, waiting for it to finish if it has not.
Let the other tasks that can run go first.