Skip to content

Select

Wait across tasks and streams, run exactly one arm, and account for every source you did not pick.

select waits across several completion sources and runs the body of the first one that becomes ready. It is syntax and needs no import, nor do the spawns that feed it below; a file that names a source’s type (task.Stream[int]) or makes one (task.Stream.new[int](8), time.after(d)) says import task or import time.

fn fetch_left() int { println("left") return 1 }
fn fetch_right() int { println("right") return 2 }

fn first_answer() int {
    left := spawn { fetch_left() }
    right := spawn { fetch_right() }
    mut chosen := 0

    select {
        value := left => chosen = value.unwrap_or(0)
        value := right => chosen = value.unwrap_or(0)
    }

    return chosen
}

Exactly one arm body runs. The other sources keep running and stay yours.

An arm binding is T?, not T. The arm materializes its winner through await, and that answers an Option: None is a task that was cancelled, or a stream that is closed and drained. Every arm body therefore has to say what the absent case means to it — unwrap_or when nothing in the program cancels, a match when the difference matters.

select is a statement

It evaluates to void. Results leave through enclosing mutable state, or by returning from an arm body — never as the value of the select itself.

fn work() int { return 1 }

fn pick() int {
    task := spawn { work() }
    chosen := select {
        value := task => value
    }
    return chosen
}

That reports ATOLL2002: expected 'int', found 'void'. The two working shapes are a mutable local, as above, or a direct return:

fn fetch_left() int { return 1 }
fn fetch_right() int { return 2 }

fn first_answer() int {
    left := spawn { fetch_left() }
    right := spawn { fetch_right() }

    select {
        value := left => return value.unwrap_or(0)
        value := right => return value.unwrap_or(0)
    }

    return 0
}

Arm bodies are ordinary statements: they can return, break, continue, raise an error, or mutate enclosing state — wherever those are legal in the surrounding context.

Arm structure

pattern := source => body

The source must satisfy the compiler’s structural Selectable[T] protocol — raw_handle(): u64 plus await(): T?. Task[T] and Stream[T] from task and Deadline from time all do. Source expressions are evaluated once, before the wait begins, so bind anything non-trivial to a named local first.

A type with neither method is refused rather than substituted for. A literal 0 standing in for the missing handle would make select_arm(0) name task zero, which is the root — so an arm over an ordinary struct would register the program on itself and bind the struct where the source’s value belongs, with no diagnostic anywhere.

The binding pattern is checked against the source’s produced type, which is that T?, and it cannot be one that fails: an arm has nowhere to go when its pattern does not match, so Some(v) := source is ATOLL1094. Bind a name and test it in the body. Use _ when the arm cares that the source fired, not what it carried:

import task

fn work() int { return 1 }

fn drain_signal() int {
    events := task.Stream.new[int](8)
    shutdown := spawn { work() }
    mut total := 0
    mut running := true

    for running {
        select {
            v := events => {
                match v {
                    Some(n) => total = total + n
                    None => running = false
                }
            }
            _ := shutdown => running = false
        }
    }

    return total
}

For a task, selection consumes and reaps the winning task. For a stream, it receives the next value and leaves the stream usable for the next iteration. Do not place the same single-consumer task in two arms — both refer to one result and one reaping obligation.

The stream arm’s await is recv, so its None carries the same meaning it does anywhere else: closed and drained, with nothing further coming. Ending the loop on it, as above, is usually the right response.

Selecting inside a loop

The loop-plus-select shape is how a coordinator multiplexes long-lived sources. break from an arm body exits the loop, not just the selection.

fn work(n int) int { return n }

fn wait_for_one() int {
    task := spawn { work(9) }
    mut got := 0

    for {
        select {
            value := task => {
                got = value.unwrap_or(0)
                break
            }
        }
    }

    return got
}

Timeouts

time.after(d) is a deadline, and a deadline is an ordinary arm. That is the whole of the timeout surface — no new syntax, and nothing a selection has to be told about:

import time

fn slow() int { time.sleep(time.Duration.of_millis(400)) return 1 }

fn bounded() int {
    task := spawn { slow() }
    mut answer := 0

    select {
        value := task            => answer = value.unwrap_or(0)
        _ := time.after(time.Duration.of_millis(50)) => answer = 0 - 1
    }

    task.cancel()
    return answer
}

A deadline is one entry in a slab the scheduler reuses — no task, no frame, no coroutine stack, and no allocation once a program reaches its own steady state. That matters because a timeout is the one wait taken out speculatively: a server that bounds every request holds one per request and throws almost all of them away unfired, so arming and disarming is the cost, not firing. The withdrawal that removes a losing arm is the same line that disarms the deadline, so a timeout that did not fire cannot be left behind.

A deadline is anchored where time.after is written, not where it is registered, which is what lets one bound a whole loop instead of each iteration:

import time

fn attempt() int { time.sleep(time.Duration.of_millis(30)) return 1 }

fn within_budget() int {
    budget := time.after(time.Duration.of_seconds(5))
    mut got := 0
    mut i := 0

    for i < 100 && got == 0 {
        task := spawn { attempt() }
        select {
            value := task  => got = value.unwrap_or(0)
            _ := budget    => i = 100          // the WHOLE five seconds
        }
        task.cancel()
        i = i + 1
    }

    return got
}

Writing time.after(...) inside the loop gives each attempt its own five seconds instead. The difference is visible in where it is written rather than in a rule.

with_timeout

Bounding a single wait needs no select at all. Task[T] and Stream[T] both have with_timeout(d), which answers time’s Timed[T]:

import time

fn slow() int { time.sleep(time.Duration.of_millis(400)) return 1 }

fn describe() string {
    task := spawn { slow() }
    answer := match task.with_timeout(time.Duration.of_millis(50)) {
        Ready(v)  => "got ${v}"
        Over      => "cancelled"
        TimedOut  => "too slow"
    }
    task.cancel()
    return answer
}

A match on a Timed value names its variants bare, as above; built as an expression, one is time.Ready(v).

Three variants because a bounded wait ends three ways, and the last two are the pair a caller must be able to tell apart: TimedOut is a source that is still live, where asking again is meaningful; Over is a cancelled task or a closed and drained stream, where it is not. An answer of T? would fold them together and leave the caller unable to make exactly the decision it is making.

A timeout does not cancel. The source is left alone, so TimedOut followed by another with_timeout waits some more, and giving up on the work as well as on waiting for it is the cancel above — which stays yours to write, because “I will not wait any longer” and “nobody should do this work” are different intentions.

default arms

Adding default makes the selection non-blocking. The runtime scans the sources once; if none is ready, it runs default instead of registering waiters and parking.

import task

fn handle(message int) void { println("message ${message}") }
fn bounded_work() void { println("tick") }

fn poll_loop(rounds int) void {
    inbox := task.Stream.new[int](8)
    mut i := 0
    mut open := true

    for i < rounds && open {
        select {
            message := inbox => {
                match message {
                    Some(m) => handle(m)
                    None => open = false
                }
            }
            default => bounded_work()
        }
        i = i + 1
    }
}

This is the poll-and-work pattern: drain what is ready, otherwise do a slice of background work. Keep the default body bounded. A tight loop whose default does nothing and reaches no other safepoint starves everything else on the scheduler.

default is also how you write a non-blocking “is anything ready?” check without committing to a wait.

Losing sources are still yours

Selection removes the temporary wait registrations. It does not cancel the sources it did not pick — that is the whole difference from race, which owns its arm tasks and cancels the losers.

With two alternatives, a boolean ledger is enough:

fn fetch_left() int { return 1 }
fn fetch_right() int { return 2 }
fn use_value(v int) void { println("got ${v}") }

fn pick_one() void {
    left := spawn { fetch_left() }
    right := spawn { fetch_right() }
    mut left_won := false

    select {
        value := left => {
            left_won = true
            use_value(value.unwrap_or(0))
        }
        value := right => use_value(value.unwrap_or(0))
    }

    if left_won {
        right.cancel()
    } else {
        left.cancel()
    }
}

The winner has already been consumed — never await or cancel it again.

Beyond two arms, use an explicit enum ledger. A boolean stops scaling the moment a third source appears:

enum Winner {
    Cache
    Replica
    Origin
}

fn from_cache() int { return 1 }
fn from_replica() int { return 2 }
fn from_origin() int { return 3 }

fn lookup() int {
    cache := spawn { from_cache() }
    replica := spawn { from_replica() }
    origin := spawn { from_origin() }

    mut winner := Winner.Cache
    mut value := 0

    select {
        v := cache => {
            winner = Winner.Cache
            value = v.unwrap_or(0)
        }
        v := replica => {
            winner = Winner.Replica
            value = v.unwrap_or(0)
        }
        v := origin => {
            winner = Winner.Origin
            value = v.unwrap_or(0)
        }
    }

    match winner {
        Winner.Cache => {
            replica.cancel()
            origin.cancel()
        }
        Winner.Replica => {
            cache.cancel()
            origin.cancel()
        }
        Winner.Origin => {
            cache.cancel()
            replica.cancel()
        }
    }

    return value
}

The ledger is application state. select returns void deliberately: it makes the “who won, and what do I owe them” question explicit rather than hiding it in a result value.

Failures in arm bodies

An arm body can propagate an error out of the enclosing function like any other statement.

error ArmError { Bad }

fn risky() int ! ArmError {
    error Bad
}

fn run() int ! ArmError {
    task := spawn { risky() }
    mut got := 0

    select {
        outcome := task => {
            match outcome {
                Some(result) => got = result?
                None => got = 0
            }
        }
    }

    return got
}

Note the two layers. outcome is the arm’s T?, and its None is the task having been cancelled; the Some holds the Result[int, ArmError] the child produced, and the ? inside the arm body applies the enclosing function’s error policy to that. A cancelled task is not an error, so it does not travel the error channel — the arm decides what to do about it.

Fairness

When several sources are already ready, a select takes the one it took longest ago, and among sources it has never taken, the arm written first. Each source (a stream’s side, a task) remembers when a select last took it over another ready arm, so a source that stays ready is taken within as many runs of a select as it has arms: two full streams are drained in turn, and a closed, drained stream, whose arm is always ready, keeps no other arm from being taken. A source shared by several selects is served in turn across all of them.

The choice is deterministic: no seed and no clock, so a program takes the same arms on every run. A select with one ready arm reads and writes no stamp; one with several reads a stamp for each ready arm and writes the winner’s.

Empty selections

select {} is accepted as a void no-op. It does not suspend and introduces no effects.

fn nothing() void {
    select {}
}

It is rarely what you want: an empty selection usually means the arm set is being constructed dynamically, which belongs in a higher-level abstraction.

Effects

At runtime a selection waits and consumes one winner. It spawns nothing and cancels nothing. The current checker is more conservative and records Spawn, Suspend, and Cancel for any non-empty selection — including one with a non-blocking default arm. Treat that row as an analysis over-approximation, not as a description of behaviour, and declare it when you annotate a function that contains a select.

Checklist

Before entering a selection:

  1. bind each source to a named local exactly once;
  2. know which sources are single-use (Task) and which are reusable (Stream);
  3. decide what each arm does with a None — a cancelled task, a drained stream;
  4. decide how end-of-stream or shutdown is represented;
  5. decide what happens to every loser — cancel, keep, or hand off;
  6. count on fairness as it is given: the ready arm taken longest ago first, ties by arm order, the same on every run;
  7. keep any default body bounded;
  8. make sure arm-body errors fit the enclosing function’s error contract.

Reach for race instead when the construct itself should own the competitor tasks and cancel the losers for you.

Type to search…

↑↓ navigate↵ selectEsc close