---
title: "Concurrency"
description: "Spawn tasks, join them, race them, select over them, and move values through streams — all with ordinary call syntax."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Concurrency

> **This surface runs**
>
> `spawn`, `Task[T]` (`await`, `join`, `cancel`), `race`, `Stream[T]` and
> `time.sleep` are lowered by `crates/atoll-codegen` and driven by the scheduler in
> `crates/atoll-runtime`, and they are covered by tests. The continuation ABI
> underneath is the one every suspending call uses: a call crosses a frame and
> comes back, `spawn` mints a frame the scheduler owns, and a cancelled task
> resumes on its own edge so what it holds is released.
>
> `select` lowers and its `Task` arms run, but there is no end-to-end fixture for
> it yet and a `Stream` arm is refused by the scheduler — see
> [Select](https://docs.atoll.workreef.dev/language/concurrency/select/).

Atoll has one function kind: `fn`. There is no `async fn`, no `await` keyword,
and no coloring split between "sync" and "async" callers. A function that may
pause is described by its *effect row*, not by its declaration syntax.

Everything explicit about concurrency happens through five constructs:
`spawn`, `Task[T]`, `race`, `select`, and `Stream[T]`.

`spawn`, `race` and `select` are syntax, and `await`, `join`, `cancel`, `send`
and `recv` are methods on the value in hand, so none of them needs an import —
the first example below has none. The two types belong to the standard
library's `task` module, a module like any other rather than a root name: a file that
names one, as in a parameter `queue task.Stream[int]` or a list
`[]task.Task[int]`, or that calls `task.Stream.new[int](8)` or
`task.yield_now()`, says `import task`. Waiting for a span of time is
`time.sleep(d)`, from `import time`.

```atoll run=42
fn double(n int) int {
    return n * 2
}

fn main() int {
    left := spawn { double(10) }
    right := spawn { double(11) }
    return left.await().unwrap_or(0) + right.await().unwrap_or(0)
}
```

Both children start before either join runs, so their work overlaps. `.await()`
is a *method* on `Task[int]`; it joins the child, yields its result, and reaps
the finished task.

It answers `int?`, not `int`. **`None` means the task was cancelled, and nothing
else** — a cancelled body never returned, so there is no value in existence to
hand back. A task that ran to its end always answers `Some`, whatever it
computed. Neither of these children can be cancelled, so `unwrap_or(0)` is the
honest way to spend the `Option`; when cancellation is the point, match on it.

| Construct | Purpose | Result |
| --- | --- | --- |
| `spawn expr` / `spawn { ... }` | Start a child task | `Task[T]` |
| `t.await()` | Join, retrieve, reap | `T?` (`None` ⟺ cancelled) |
| `t.join()` | Wait for the task to be over, without its value | `bool` (`false` ⟺ cancelled) |
| `t.cancel()` | Request cooperative cancellation | `void` |
| `race { a  b }` | First arm to complete; losers cancelled | The arms' unified type, under `?` |
| `select { p := src => body }` | Run one arm when its source is ready | `void` (statement) |
| `task.Stream.new[T](cap)` | Shared bounded channel | `Stream[T]` |

There is no `spawn.all`, no `async fn`, no `await` keyword, and no `concurrent`
block in the current language.

## Fan-out and fan-in

The common shape is: start every independent unit of work, then collect. Handles
can live in a list, which makes the fan width a runtime value.

```atoll
import task

fn fetch_shard(shard int) int {
    return shard * 100
}

fn total(shards int) int {
    mut running: []task.Task[int] = []
    for shard in 0..shards {
        running.push(spawn { fetch_shard(shard) })
    }

    mut sum := 0
    for Some(t) := running.pop() {
        sum = sum + t.await().unwrap_or(0)
    }
    return sum
}
```

Note the two separate loops. Awaiting inside the first loop would serialize the
whole thing: each child would finish before the next one started.

Two more details are load-bearing. The fan-out loop binds `shard` per iteration
rather than counting with a `mut` local, because a spawned task outlives the
frame that started it and a `mut` binding captures by **reference** — capturing
one is `ATOLL1060`. The collect loop **drains** the list rather than iterating
it, because `await` consumes the handle: a `Task[T]` owes a `drop` and carries no
reference count, so there is no second reference for `for t in running` to
hand out — `for Some(t) := running.pop()` is the same drain form the worker
loop below uses on a `Stream`.

## Errors cross task boundaries as values

A spawned body that returns `T ! E` produces a `Task[Result[T, E]]`. Awaiting it
hands you `Result[T, E]?` — the `Option` answers whether the child finished at
all, the `Result` answers what it produced — and once the `Some` is opened, `?`
applies the caller's error policy as usual. The two do not collapse into one
another: a cancelled child did not fail, it never ran to a conclusion.

```atoll
error LoadError {
    NotFound { id: int }
    Corrupt
    Cancelled
}

struct Profile { id int, name string }
struct Orders { count int }
struct Page { profile Profile, orders Orders }

fn load_profile(id int) Profile ! LoadError {
    if id < 0 { error NotFound { id: id } }
    return Profile { id: id, name: "ada" }
}

fn load_orders(id int) Orders ! LoadError {
    if id < 0 { error NotFound { id: id } }
    return Orders { count: 3 }
}

fn load_page(id int) Page ! LoadError {
    profile_task := spawn { load_profile(id) }
    orders_task := spawn { load_orders(id) }

    profile := match profile_task.await() {
        Some(result) => result?
        None => error Cancelled
    }
    orders := match orders_task.await() {
        Some(result) => result?
        None => error Cancelled
    }
    return Page { profile: profile, orders: orders }
}
```

If the first `?` fires, the second child is still running. That is a real
decision, not an oversight to ignore — see
[Cancellation](https://docs.atoll.workreef.dev/language/concurrency/cancellation/) for the patterns that close
it.

## Streams carry sequences

`Stream[T]` is a shared handle to a bounded FIFO ring. Copies of the handle —
including copies captured by a spawned body — alias the same channel, which is
what makes producer/consumer pairs work.

```atoll
import task

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

fn consume() int {
    events := task.Stream.new[int](4)
    producer := spawn { produce(events, 10) }

    mut total := 0
    for Some(v) := events.recv() {
        total = total + v
    }

    producer.join()
    return total
}
```

The capacity of `4` bounds how far ahead the producer may run. Both sides park:
`send` suspends while the ring is full, `recv` suspends while it is empty, and
each is woken by the other. A bare name may suspend and a `try_` name never
does — `try_send` and `try_recv` are the non-blocking forms. The two `None`s
differ by the same rule: `recv`'s means closed *and* drained, `try_recv`'s only
means empty at this instant.

`producer.join()` is the wait without the value. The producer is a `Task[void]`,
so there is nothing to collect from it — only the fact that it has stopped.

## Race picks the first completion

```atoll
fn from_cache(key int) int {
    return key
}

fn from_origin(key int) int {
    return key + 1
}

fn lookup(key int) int {
    winner := race {
        from_cache(key)
        from_origin(key)
    }
    return winner.unwrap_or(key)
}
```

Each arm becomes a child task. The first to *complete* wins; every other arm is
cancelled. This is a completion race, not a success race — an arm that fails
first still wins.

`race` answers `T?` for the same reason `await` does, and because it *is* an
`await`: the winner is materialized through its handle. The winner is not
cancelled by the race, but nothing stops somebody else cancelling it, and
answering a bare `T` would mean inventing one.

## Select dispatches on readiness

`select` waits across heterogeneous sources and runs exactly one arm's body. It
is a statement and evaluates to `void`, so results leave through enclosing
mutable state or a `return`.

```atoll
import task

fn tick() int { return 1 }

fn pump() int {
    events := task.Stream.new[int](8)
    shutdown := spawn { tick() }

    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
}
```

An arm's binding is `T?`, because an arm materializes its source through
`await`: a task arm's `None` means that task was cancelled, and a stream arm's
means the stream is closed and drained. That is why the `events` arm can decide
to stop.

Unlike `race`, `select` does not cancel the sources it did not choose. They stay
alive and stay yours.

## Effects describe what a function may do

Every function has a row drawn from `Suspend`, `Error`, `Alloc`, `Spawn`, and
`Cancel`. The compiler computes it by inference — in practice you never write
one, and the code in this chapter carries no effect annotations.

```atoll
import task

fn pure_math(n int) int {
    return n * n
}

fn may_pause(n int) int {
    task.yield_now()
    return n * n
}

fn starts_children(n int) int {
    return (spawn { pure_math(n) }).await().unwrap_or(0)
}
```

Declaring a row that omits an inherited effect produces the `ATOLL2032`
*warning*; declaring one that includes it produces the `ATOLL2031` *hint*, which
just reports where the effect came from. Declaring none — the usual case —
produces neither. Neither is an error.
[Effects](https://docs.atoll.workreef.dev/language/concurrency/effects/) covers both in detail.

## Execution model

Scheduling is cooperative. A running task keeps executing until it reaches a
suspension point — a `@suspend` host call, a task join, a blocking `select`, a
channel `send` or `recv`, or a generated loop safepoint — at which point
control returns to the scheduler. A program built with `--no-preempt` has no
generated safepoints, so its tasks switch only at the first five.

Tasks form a parent/child tree, so cancellation and shutdown reach a spawned
computation structurally. Dropping a `Task[T]` removes your ability to join the
child, and therefore **cancels it**: work nobody can join and nobody can stop
has no owner left. Call [`detach()`](https://docs.atoll.workreef.dev/language/concurrency/tasks/#ownership)
when fire-and-forget is what you meant.

## A composed example

A bounded work queue: one producer feeds a stream, a fixed pool of workers drains
it, and the coordinator collects their totals.

```atoll
import task

fn cost(job int) int {
    return job * job
}

fn worker(queue task.Stream[int]) int {
    mut subtotal := 0
    for Some(job) := queue.recv() {
        subtotal = subtotal + cost(job)
    }
    return subtotal
}

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

fn run(jobs int, workers int) int {
    queue := task.Stream.new[int](8)
    feeder := spawn { fill(queue, jobs) }

    mut pool: []task.Task[int] = []
    mut w := 0
    for w < workers {
        pool.push(spawn { worker(queue) })
        w = w + 1
    }

    feeder.join()

    mut total := 0
    for Some(t) := pool.pop() {
        total = total + t.await().unwrap_or(0)
    }
    return total
}
```

Every started task is joined exactly once — the feeder with `join`, because its
`void` result is nothing to collect, and each worker with `await`, because its
subtotal is the point. `for Some(job) := queue.recv()` is the drain form: it
loops while the pattern matches and stops on the first `None`, which `recv`
gives only once the stream is closed and empty.

## Reading order

Start with [Effects](https://docs.atoll.workreef.dev/language/concurrency/effects/) and
[Suspension](https://docs.atoll.workreef.dev/language/concurrency/suspension/) for the model, then
[Tasks](https://docs.atoll.workreef.dev/language/concurrency/tasks/) and
[Spawning](https://docs.atoll.workreef.dev/language/concurrency/spawning/) for the mechanics.
[Cancellation](https://docs.atoll.workreef.dev/language/concurrency/cancellation/) covers shutdown,
[Streams](https://docs.atoll.workreef.dev/language/concurrency/streams/) covers communication, and
[Select](https://docs.atoll.workreef.dev/language/concurrency/select/) and [Race](https://docs.atoll.workreef.dev/language/concurrency/race/)
cover the two multi-source constructs.

## What is built

- **Effect rows work.** `fn slow(): int using [Suspend]` and
  `using [Alloc]` both declare, lower and run.
- **`spawn`, `await`, `join`, `cancel` and `race` run.** A spawned helper is
  reached through the spawn edge rather than a call, is placed on that basis,
  and the whole program executes on the scheduler in `crates/atoll-runtime`.
- **`Stream[T]` runs in both directions.** `send` and `recv` park and are woken
  by each other, so a bounded channel gives real backpressure rather than a
  spin on `task.yield_now()`.

The continuation ABI underneath — a suspending function the scheduler drives,
a result written through an out-pointer, cancellation as the ordinary resume
path — is the same one every suspending call uses.

Source: https://docs.atoll.workreef.dev/language/concurrency/index.mdx
