# Concurrency Overview

Vex has two concurrency surfaces:

1. go blocks for detached or background work;
2. async functions and await for suspension-based workflows.

Channels provide typed communication between tasks. The runtime uses bounded
multiple-producer, multiple-consumer queues, cooperative blocking progress,
and event-driven multi-channel `select`. Channel capacity controls how far
producers can advance before a consumer makes space.

## Choose a model

| Model | Use it for | Main syntax |
| --- | --- | --- |
| go block | Scheduling a block of work | go { ... } |
| async function | A function that may suspend | async fn |
| await | Waiting for an async result | await expression |
| channel | Typed communication and backpressure | `Channel<T>`, `<-channel` |

Start with synchronous code. Add concurrency when the ownership boundary and shutdown behavior are clear.

## go blocks

A go block schedules its body independently of the current statement sequence:

~~~vex
fn main(): i32 {
    let done = Channel.new<i32>(1);
    go {
        $println("background work");
        done.send(1);
    };
    $println("main continues");
    let _ = done.recv();
    return 0;
}
~~~

The two messages can appear in either order. The final receive makes task
completion explicit before `main` returns.

The block does not make a synchronous function return a value. If the caller needs a result, use a channel or an explicit task handle provided by the relevant runtime API.

Captured values still go through ownership and escape analysis. A borrowed local cannot be moved into a detached block if that would leave a dangling reference or create an unsafe shared mutation.

## Channels

Channels are typed queues. A bounded channel makes the producer and consumer relationship explicit:

~~~vex
fn main(): i32 {
    let! channel: Channel<i64> = Channel(1);

    go {
        channel.send(42);
    };

    let value = <-channel;
    $println(value);
    return 0;
}
~~~

The receive operator is blocking and returns the element type directly. A drained closed channel produces that type's zero value. Use `recv()`, `recvResult()`, or `tryRecv()` when the caller must distinguish closure or non-readiness. See [Channels](channels.md).

## async and await

An async function can be awaited from another async context:

~~~vex
async fn fetch_value(): i32 {
    return 42;
}

async fn main(): i32 {
    let value = await fetch_value();
    $println(value);
    return 0;
}
~~~

Await is not valid in an ordinary synchronous function. An async function's runtime behavior depends on the runtime support available for the target and the operation being awaited.

## Ownership at concurrency boundaries

Concurrency does not disable the ownership model. The compiler checks captures at a go or async boundary:

~~~text
let! values = Vec.new<i32>()
let borrowed = &values

go {
    use(borrowed)
}
~~~

Whether a capture is accepted depends on the lifetime and capture kind. Prefer moving an owned value into a task, borrowing only when the task is guaranteed to remain within the borrow's lifetime, and communicating results through a channel.

For bounded iteration such as `go(cpu: 4) for item in bundle.items { ... }`, an
independently owned source field can move into the task without moving
`bundle.label`. This also covers nested generic fields and user-defined
iterators; it is not a special privilege of `Vec`. An iterator call such as
`bundle.items.iter()` stays inside the task, after its source owner is transferred,
so it cannot leave a borrow pointing into the spawning function's storage.

This precise source transfer does not permit reading the moved field again or
moving it while a live borrow exists. A custom destructor or sharing protocol on
an enclosing aggregate, an indexed/borrowed source place, or use of the same root
inside the loop body retains the existing whole-root capture rules. It is not a
promise of field-by-field capture for every closure or `go { ... }` block.

## Designing for the runtime

A producer can wait when its bounded queue is full; a receiver can wait when
that queue is empty. Give every wait an owner responsible for making progress
or initiating shutdown. Close a channel only after its final producer is done,
and drain the buffered values when delivery matters.

For portability, consult [Platform Support](../platform-support.md). Measure
throughput and latency with the workload and runtime configuration you intend
to deploy; queue capacity and task count are application choices.

## Next steps

- [Collecting Fallible Task Results](batch-results.md)
- [Channels](channels.md)
- [Async](async.md)
- [Borrowing](../memory/borrowing.md)
- [Language Status](../language-status.md)
