# 11.3 Channels and Select

> A channel is a fixed-capacity queue through which some tasks send values and others receive them, in order and without sharing memory.

Web page: https://pseudolearn.app/en/spec/tareas/canales

> **In one sentence**
>
> A channel is a fixed-capacity queue through which some tasks send values and others receive them, in order and without sharing memory.

## 11.3.1 How it works

`Channel<T>` is the type and `Channel(n)` creates one with capacity `n`. Three operations:

| Operation | What it does |
| --- | --- |
| `Await c.send(v)` | queues `v`; if full, it waits. Returns `False` if the channel is closed |
| `Await c.receive()` | takes the first one as `Something(v)`; if empty, it waits. Closed and empty gives `Nothing` |
| `c.close()` | closes the channel without losing what is queued |

**Figure 11.3-1: A channel of capacity 2**

A producer on the left sends values into a channel with two slots holding 20 and 10; a consumer on the right receives them in order.

A channel of capacity 2. The producer waits when it is full; the consumer, when it is empty. Values come out in the order they went in.

### Program: A producer and a consumer

```pseudolearn
Subroutine Suspendable Productor(canal As Channel<Integer>)
  For i <- 1 To 3 Do
    If Not Await canal.send(i * 10) Then
      Break;
    EndIf
  EndFor
  canal.close();
EndSubroutine

Algorithm Tuberia
  Define canal As Channel<Integer> <- channel(2);
  Tasks
    Spawn Productor(canal);
    Define seguir As Boolean <- True;
    While seguir Do
      Switch Await canal.receive() Do
        Some(valor):
          Write "recibido ", valor;
        None:
          seguir <- False;
      EndSwitch
    EndWhile
  EndTasks
EndAlgorithm
```

**Output**

```text
recibido 10
recibido 20
recibido 30
```

*The program finishes normally.*

## 11.3.2 Select

`Select` waits on **several** channels at once and serves the first one that has something. If several are ready, the first written branch wins: the result is always the same.

### Program: Serving whichever arrives first

```pseudolearn
Subroutine Suspendable Avisar(canal As Channel<String>)
  If Await canal.send("aviso urgente") Then
    canal.close();
  EndIf
EndSubroutine

Subroutine Anunciar(origen As String, mensaje As Optional<String>)
  Switch mensaje Do
    Some(texto): Write origen, ": ", texto;
    None: Write origen, ": cerrado";
  EndSwitch
EndSubroutine

Algorithm Elige
  Define noticias As Channel<String> <- channel(1);
  Define avisos As Channel<String> <- channel(1);
  Tasks
    Spawn Avisar(avisos);
    Select
      Receive n From noticias:
        Anunciar("noticias", n);
      Receive a From avisos:
        Anunciar("avisos", a);
    EndSelect
  EndTasks
EndAlgorithm
```

**Output**

```text
avisos: aviso urgente
```

*The program finishes normally.*

> **Limit**
>
> - Capacity is at least 1; a smaller constant is `channelCapacityInvalid`.
> - Only transferable values travel: no objects or records containing objects.
> - `Select` needs at least two branches.

**In short**
- A channel is a bounded queue between tasks.
- `send` and `receive` are used with `Await`; `close`, without it.
- `Select` serves the first ready channel, ties broken by written order.

**See also**
- [11.2 Task scopes with Tasks and Spawn](https://pseudolearn.app/en/spec/tareas/ambitos.md)
- [3.10 Optional and Result](https://pseudolearn.app/en/spec/tipos/opcional-resultado.md)
