Skip to content

Spawning

Start child tasks with spawn, control what they capture, and give every handle an explicit outcome.

spawn starts one child task and evaluates to Task[T], where T is the type of the spawned expression. It takes either a bare expression or a block. spawn is syntax and the handle’s methods come with it, so neither needs an import; Task itself is the task module’s, and a file that writes the type out, as cleanup: task.Task[void] does below, says import task.

fn fetch_booking(id int) int {
    return id * 2
}

fn start(id int) int {
    task := spawn fetch_booking(id)
    return task.await().unwrap_or(0)
}

The expression is scheduled as child work; it is not evaluated to completion before the handle comes back. The Spawn and Suspend effects both arrive with it — Spawn because a child is created, Suspend because the join can pause.

await() answers T?, not T. None means the task was cancelled and nothing else: a cancelled body never returned, so there is no T to hand back. Nothing cancels this child, so unwrap_or(0) spends the Option without hiding anything; where cancellation is a real outcome, match on it.

Block form

A block lets a child do setup, several statements, or its own control flow. The block’s tail expression is the task’s result.

fn fetch_booking(id int) int { return id * 2 }
fn render_booking(booking int) string { return "booking ${booking}" }

fn start(id int) string {
    task := spawn {
        booking := fetch_booking(id)
        render_booking(booking)
    }
    return task.await().unwrap_or("")
}

A block with no value-producing tail yields Task[void]:

import task

fn remove_expired_entries() void {
    println("sweeping")
}

fn sweep() void {
    cleanup: task.Task[void] = spawn {
        remove_expired_entries()
    }
    if !cleanup.join() {
        println("the sweep was cancelled")
    }
}

join() is the wait without the value: it suspends until the task is over and answers true if it completed, false if it was cancelled. That is the right call whenever the result is not what you came for — a Task[void] has nothing to collect, and t.cancel() followed by t.join() is the “stop it, and do not carry on until it has actually stopped” pattern.

The tail can be an arbitrary expression, so a child can compute several intermediates and return their combination:

fn measure(sample int) int { return sample * sample }

fn start() int {
    task := spawn {
        low := measure(3)
        high := measure(9)
        high - low
    }
    return task.await().unwrap_or(0)
}

Spawn is an expression, not a statement

spawn { ... } produces a value, the Task it started. In the tail position of a void function the value is dropped, as the last line of any void block drops what it answers; bind it (t := spawn { ... }) to keep the handle:

fn record_metric(event string) void {
    println(event)
}

fn emit() void {
    spawn { record_metric("started") }
}

That reports ATOLL2002: type mismatch: expected 'void', got 'Task[void]'. Bind the handle — to _ if you truly want to discard it:

fn record_metric(event string) void {
    println(event)
}

fn emit() void {
    _ := spawn { record_metric("started") }
    println("continuing")
}

In a non-tail position the value is simply dropped, so a bare spawn statement followed by more code is fine:

fn record_metric(event string) void {
    println(event)
}

fn emit() void {
    spawn { record_metric("started") }
    println("continuing")
}

Parallel start

Calls are sequential unless you spawn them. Start every child before joining any of them, or you get no overlap at all.

struct Profile { name string }
struct Orders { count int }

fn load_profile(user_id int) Profile { return Profile { name: "user${user_id}" } }
fn load_orders(user_id int) Orders { return Orders { count: user_id } }

fn dashboard(user_id int) (Profile, Orders) {
    profile_task := spawn { load_profile(user_id) }
    orders_task := spawn { load_orders(user_id) }

    profile := profile_task.await().unwrap_or(Profile { name: "unknown" })
    orders := orders_task.await().unwrap_or(Orders { count: 0 })
    return (profile, orders)
}

This is the replacement for the removed spawn.all { ... } form; there is no such construct in the language today.

Spawn order controls when each child becomes eligible to run, not which one runs first. Only messages, selection, or an actual join constrain visible completion order.

Join discipline

Once a child is started, pick exactly one outcome for it:

  • await it and consume its result;
  • join it when only the fact that it is over matters;
  • cancel it because its result is no longer wanted, and join it if you need to know it has actually stopped;
  • hand the Task[T] to another owner who will do one of those;
  • deliberately discard the handle under a documented best-effort policy.

Early exits are where this accounting slips. When one join fails, the sibling is still running:

error JoinError { LeftFailed, RightFailed, Cancelled }

fn load_left() int ! JoinError { return 1 }
fn load_right() int ! JoinError { error RightFailed }
fn combine(a int, b int) int { return a + b }

fn both() int ! JoinError {
    left := spawn { load_left() }
    right := spawn { load_right() }

    left_result: Result[int, JoinError] = match left.await() {
        Some(result) => result
        None => {
            right.cancel()
            error Cancelled
        }
    }
    left_value := left_result catch {
        LeftFailed => {
            right.cancel()
            error LeftFailed
        }
        RightFailed => {
            right.cancel()
            error RightFailed
        }
        Cancelled => {
            right.cancel()
            error Cancelled
        }
    }

    right_value := match right.await() {
        Some(result) => result?
        None => error Cancelled
    }
    return combine(left_value, right_value)
}

Each failing arm cancels the sibling before leaving. The exact error mapping is yours to choose; the rule that does not vary is that a started sibling must not become unobserved work just because another join failed first.

Awaiting a fallible child opens two envelopes. await() gives Result[int, JoinError]?: the Option says whether the child reached an end at all, and only the Result inside it says how. None is not a failure the child reported — it is a child that was cancelled and therefore reported nothing — so it needs its own arm rather than being folded into the error mapping.

Captures

A spawned block may reference values from the enclosing function. The compiler builds a task body with hidden capture parameters.

import task

struct Booking { id int }

fn load_booking(id int) Booking {
    return Booking { id: id }
}

fn schedule(id int) task.Task[Booking] {
    prefix := "booking"
    return spawn {
        println("${prefix}:${id}")
        load_booking(id)
    }
}

Capture the smallest stable value the child actually needs, not the graph it was reached through:

import task

struct User { id int, name string }
struct Request { user User, headers []string, body []byte }
struct Profile { user_id int }

fn load_profile(user_id int) Profile {
    return Profile { user_id: user_id }
}

fn start(request Request) task.Task[Profile] {
    user_id := request.user.id
    return spawn {
        load_profile(user_id)
    }
}

Capturing request would keep the headers and body alive for as long as the child runs, to read one integer.

Captures are values, moved into the task and never lent: the task outlives the statement that spawned it, and nothing waits for a loan. So the parent reading a capture that owns a block after the spawn is a read after a move (ATOLL3102); .clone() the value first where both need it, as user_id above copies the one integer the child reads.

fn main() int {
    name := "abc"
    t := spawn { name.len() }
    n := match t.await() { Some(k) => k None => 0 }
    return n + name.len()          // ATOLL3102: `name` moved into the task
}

Assigning to a captured local inside the child does not mutate the parent’s binding, and a captured mut local is not a synchronized shared cell. For genuinely shared state, use a Stream[T] — its handle deliberately aliases one control block across copies:

import task

fn tally(out task.Stream[int], upto int) void {
    mut i := 1
    for i <= upto {
        if !out.send(i) { return }
        i = i + 1
    }
    out.close()
}

fn run() int {
    results := task.Stream.new[int](4)
    worker := spawn { tally(results, 5) }

    mut total := 0
    for Some(v) := results.recv() {
        total = total + v
    }
    worker.join()
    return total
}

Both results handles refer to the same ring, which is why the parent sees what the child sent. recv suspends while the ring is empty and answers None only once the stream is closed and drained, so the drain loop needs no separate is_closed check — and join waits for the producer without asking a Task[void] for a value it does not have.

Fallible bodies

The spawned body is checked exactly like a function body. When it returns a Result, the handle is Task[Result[T, E]] and awaiting hands you Result[T, E]? — that result, under the cancellation answer.

error ProfileError { Missing, Cancelled }

struct Profile { user_id int }

fn load_profile(user_id int) Profile ! ProfileError {
    if user_id < 0 { error Missing }
    return Profile { user_id: user_id }
}

fn fetch(user_id int) Profile ! ProfileError {
    task := spawn { load_profile(user_id) }
    match task.await() {
        Some(result) => return result?
        None => error Cancelled
    }
}

Discarding a fallible task also discards the only place its failure could be observed. Do that only when the child handles its own errors.

Nesting

A child can spawn its own children; the descendants stay in the same structured tree, so cancelling an ancestor reaches them.

fn stage(n int) int {
    println("stage ${n}")
    return n
}

fn pipeline() int {
    outer := spawn {
        inner := spawn { stage(2) }
        stage(1) + inner.await().unwrap_or(0)
    }
    return outer.await().unwrap_or(0)
}

Child completion does not publish anything to the parent by itself. The typed handle is the transfer point; a Stream[T] is the separate multi-value protocol.

Fire-and-forget

Discarding a handle starts work with no source-level join.

fn record_metric(event string) void {
    println(event)
}

fn handle_request(path string) int {
    n := path.len()
    spawn { record_metric("request ${path}") }
    return n
}

A task outlives the statement that made it, so it takes what it captures, a mut local as much as any other: reading path after the spawn is refused (ATOLL3102). Read it first, as here, or give the task a .clone() of its own. No loan holds a task back, so nothing it captures is lent to it: what it took is its own, and it may keep it, in a field of a value it builds or as an argument a callee owns.

This is still a child in the task tree, not a detached process. Use it only when the result is genuinely irrelevant, failures have a boundary policy, and parent shutdown ending the work is acceptable. “Fire-and-forget” is not an unbounded background queue: cap the concurrency, tolerate cancellation, and handle errors inside the child.

At a library boundary, prefer returning Task[T] to discarding it internally. The caller can then decide whether to join, cancel, race, or transfer ownership.

On another reactor

A program run on a group of reactors places work with a handle to one of them. task.reactor(i) is reactor i of the group, and r.spawn { ... } runs the block once as a task of r’s. It answers a Task[T] that is awaited, selected, cancelled and joined as any other task is.

import task

fn checksum(x int) int {
    return x * 31 + 7
}

fn main() int {
    r := task.reactor(1)
    k := 12
    t := r.spawn { checksum(k) }
    println("${t.await() ?? 0}")
    return 0
}

The block’s captures move with it. A block written where it is placed, whose captures hold no count (numbers and structs of them), runs on r. One that captures a string or a list, which it would count and drop from there, runs here, as spawn would run it. So does a closure handed over in a variable, whose environment another name may still hold. On a reactor in no group, every reactor stands for this one.

Effects

spawn adds Spawn and Suspend to the enclosing row. Effects used inside the child body are analysed while checking the enclosing function, so they can widen the parent’s inferred row too:

error ChildError { Failed }

fn risky() int ! ChildError {
    error Failed
}

fn parent() int {
    task := spawn { risky() }
    match task.await() {
        Some(result) => return result.unwrap_or(0)
        None => return 0
    }
}

parent never writes error itself, and it discharges both envelopes — the cancellation Option with a match, the Result inside it with unwrap_or — but Error still shows up on the call edge into the spawn body. Account for that when you write an explicit public row.

Type to search…

↑↓ navigate↵ selectEsc close